对java线程join方法的理解

先上代码:
public class ThreadA extends Thread {

@Override
public 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 {
@Override
public void run() {
System.out.println("B start...");
ThreadA t = new ThreadA();
try {
t.start(); //1
t.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...");
}
}


运行结果如下:
[quote]
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...
[/quote]
如果将注释标记1处的那行注释掉,则threadA不会启动,即join方法会检查线程是否启动,若未启动,则什么都不做。
若启动,则调用join的这个线程获得控制权,必须等这个线程结束后,才能继续当前线程的执行。
所以若将注释标记2处的那行注释掉,main线程将提早结束,不会等到threadB结束后再结束。而threadB并不会受main线程影响。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值