线程中jion方法

以前在看More Java Pitfalls时候,上面在第一个item的时候提到了线程的jion()方法,当时没怎么懂,想try下又苦于身边没电脑,所以那一放就忘了,今天突然想起就写了程序try了一下,大概明白了其意思


public class ThreadTestSupport extends Thread {
 public void run() {
  System.out.println("run in thread!");
  try {
   sleep(9000);
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println("run in thread!");
 }
}

public class ThreadTest {
 public static void main(String[] args) {
  Thread t1 = new Thread(new ThreadTestSupport());
  t1.start();
  try {
   t1.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("run out the method!");
 }

}

运行ThreadTest.java其运行如下:
run in thread!
run in thread!
run out the method!


public class ThreadTest {
 public static void main(String[] args) {
  Thread t1 = new Thread(new ThreadTestSupport());
  t1.start();
  System.out.println("run out the method!");
 }

}

如果将ThreadTest.java改成如上代码,则运行结果如下:
run out the method!
run in thread!
run in thread!

所以就可以很明白api中对jion:等待该线程终止。

也就是说如果使用Thread.join()方法的话,必须要等Thread执行完后才执行该代码后面的代码
如果没有的话,Thread创建的线程只是运行该程序的线程的一个进程,并和其共同竞争cpu资源

但是More Java Pitfalls 上面提到的:进程有可能在线程完成前就结束 。不太明白这句话的意思,我也没try出来让进程在线程钱结束的状态 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值