总结:主线程中执行子线程Thread.join()方法会让主线程等待子线程执行完毕。等待过程中被中断会抛出中断异常。

1.主线程调用子线程的join方法后阻塞自己等待子线程返回

代码举例:

main主线程首先会在调用threadOne.join()方法后被阻塞,等待threadOne执行完毕后返回。然后主线程调用threadTwo.join()方法后再次被阻塞,等待threadTwo执行完毕后返回。

CountDownLatch工具更好用。

//等待线程终止的join方法 
        Thread threadOne = new Thread(new Runnable() { 
            @Override 
            public void run() { 
                try{ 
                    Thread.sleep(1000); 
                }catch (InterruptedException e){ 
                    e.printStackTrace(); 
                } 
                System.out.println("threadOne over"); 
 
            } 
        }); 
 
 
        Thread threadTwo = new Thread(new Runnable() { 
            @Override 
            public void run() { 
                try{ 
                    Thread.sleep(1000); 
                }catch (InterruptedException e){ 
                    e.printStackTrace(); 
                } 
                System.out.println("threadTwo over"); 
            } 
 
        }); 
 
        threadOne.start(); 
        threadTwo.start(); 
        try{ 
            threadOne.join(); 
            threadTwo.join(); 
            System.out.println("one and two thread run over"); 
        }catch (InterruptedException e){ 
            e.printStackTrace(); 
        } 
 
 
        System.out.println("main over");

输出:

threadOne over 
threadTwo over 
one and two thread run over 
main over

2.主线程调用子线程的join方法被阻塞后,又被别的线程中断后抛出InterruptedException异常

代码实例:

threadOne线程执行死循环,主线程调用threadOne的join方法阻塞自己等待线程threadOne执行完毕,待threadTwo休眠1s后会调用主线程的interrupt()方法设置主线程的中断标志,从结果看出主线程中的threadOne.join()处会抛出InterruptedException异常

public  static void  main(String[] args) { 
        Thread mainThread = Thread.currentThread(); 
        Thread threadOne = new Thread(new Runnable() { 
            @Override 
            public void run() { 
                System.out.println("threadOne start"); 
                for (;;){}//死循环 
            } 
        }); 
 
        Thread threadTwo = new Thread(new Runnable() { 
            @Override 
            public void run() { 
                try{ 
                    Thread.sleep(1000); 
                }catch (InterruptedException e){ 
                    e.printStackTrace(); 
                } 
                mainThread.interrupt(); 
            } 
        }); 
        threadOne.start(); 
        threadTwo.start(); 
        try{ 
            threadOne.join();//主线程等待threadOne,阻塞在这里。但是threadTwo启动后, 
                            //中断了mainThread,导致join中断异常 
        }catch (InterruptedException e){ 
            e.printStackTrace(); 
        } 
    }

输出:

threadOne start 
java.lang.InterruptedException 
	at java.lang.Object.wait(Native Method) 
	at java.lang.Thread.join(Thread.java:1252) 
	at java.lang.Thread.join(Thread.java:1326) 
	at com.evan.wj.ThreadTest.main(ThreadTest.java:29)


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

1.并发编程挑战