线程中jion方法

来源:互联网 发布:零点微网络是真的假的 编辑:程序博客网 时间:2024/04/27 22:50

以前在看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出来让进程在线程钱结束的状态 

原创粉丝点击