java API------Thread类join()方法

来源:互联网 发布:win10更改网络类型 编辑:程序博客网 时间:2024/05/27 00:47

join方法,“等待该线程终止“。主线程生成并起动了子线程,而子线程里要进行大量的耗时的运算(这里可以借鉴下线程的作用),当主线程处理完其他的事务后,需要用到子线程的处理结果,这个时候就要用到join()方法了。

//摘自ocjp:public class TestOne implements Runnable {public static void main (String[] args) throws Exception {Thread t = new Thread(new TestOne());t.start();System.out.print("Started");t.join();System.out.print("Complete");}public void run() {for (int i = 0; i < 4; i++) {System.out.print(i);}}}What can be a result?A. Compilation fails.B. An exception is thrown at runtime.C. The code executes and prints "StartedComplete".D. The code executes and prints "StartedComplete0123".E. The code executes and prints "Started0123Complete".Answer: E

分析:

执行t.join()后,主线程会等待子线程run()方法执行完成后再执行system.out.println("complete")语句。




0 0
原创粉丝点击