首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

对java线程join步骤的理解

2012-12-25 
对java线程join方法的理解先上代码:public class ThreadA extends Thread {@Overridepublic void run() {S

对java线程join方法的理解
先上代码:

public class ThreadA extends Thread {@Overridepublic void run() {System.out.println("A start...");for (int i = 0; i < 10; i++) {try {Thread.sleep(1000);System.out.println("ta:"+i);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("A end...");}}

public class ThreadB extends Thread {@Overridepublic void run() {System.out.println("B start...");ThreadA t = new ThreadA();try {t.start();  //1t.join();for (int i = 0; i < 3; i++) {System.out.println(i);}System.out.println("B end...");} catch (InterruptedException e) {e.printStackTrace();}}}

public class Tst {public static void main(String[] args) {System.out.println("main start...");ThreadB b = new ThreadB();b.start();try {b.join();  //2} catch (InterruptedException e) {e.printStackTrace();}System.out.println("main end...");}}


运行结果如下:
引用
main start...
B start...
A start...
ta:0
ta:1
ta:2
ta:3
ta:4
ta:5
ta:6
ta:7
ta:8
ta:9
A end...
0
1
2
B end...
main end...

如果将注释标记1处的那行注释掉,则threadA不会启动,即join方法会检查线程是否启动,若未启动,则什么都不做。
若启动,则调用join的这个线程获得控制权,必须等这个线程结束后,才能继续当前线程的执行。
所以若将注释标记2处的那行注释掉,main线程将提早结束,不会等到threadB结束后再结束。而threadB并不会受main线程影响。

热点排行