标签:final 线程 locker exception test 参数 on() xtend sse
之前看了一些博客说join就是把多线程变成单线程,其实并不是,执行join还是多线程。
class Test { public static void main(String[] args) throws InterruptedException { TestJoin t0 = new TestJoin(); TestJoin t1 = new TestJoin(); t0.start(); t1.start(); t0.join(); for(int i=0;i<100;i++){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } class TestJoin extends Thread{ @Override public void run(){ for(int i=0;i<100;i++){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } /** 结果:t0.t1线程交替打印至t0执行结束,然后开始t1,main线程交替打印。 */
结合源码看看join做了什么。
public final void join() throws InterruptedException { join(0); } public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }
执行过程(这里讨论执行无参join方法,如果执行有参数join(xx),其实就是让main线程wait(xx)):
https://blog.csdn.net/erica_1230/article/details/69388742 中介绍了:线程结束时调用的本地方法notifyAll
static void ensure_join(JavaThread* thread) { Handle threadObj(thread, thread->threadObj()); assert(threadObj.not_null(), "Java thread object must exist"); ObjectLocker lock(threadObj, thread); thread->clear_pending_exception(); java_lang_Thread::set_stillborn(threadObj()); java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED); java_lang_Thread::set_thread(threadObj(), NULL); lock.notify_all(thread); thread->clear_pending_exception(); }
结论:当一个线程a执行线程b.join()则,线程a等待至线程b执行完毕后继续执行,这个过程并不影响其线程的执行。
标签:final 线程 locker exception test 参数 on() xtend sse
原文地址:https://www.cnblogs.com/liuboyuan/p/10118236.html