Java多线程中的join方法

新建一个Thread,代码如下:

 1 package com.thread.test;
 2 
 3 public class MyThread extends Thread {
 4     private String name;
 5     public MyThread(String name) {
 6         this.name = name;
 7     }
 8     @Override
 9     public void run() {
10         for (int i = 0; i < 100; i++) {
11             System.out.println(name+"["+i+"]");
12         }
13         super.run();
14     }
15 }

之后新建测试类,代码如下:

 1 package com.thread.test;
 2 /*
 3  * 0-50执行的是主线程,50-100执行的是A线程,并且将A线程完全执行完后才继续执行主线程
 4  */
 5 public class ThreadDemo{
 6     public static void main(String[] args) {
 7         MyThread t = new MyThread("A");
 8         t.start();
 9         for (int i = 0; i < 100; i++) {
10             if (i>50) {
11                 try {
12                     t.join();
13                 } catch (InterruptedException e) {
14                     e.printStackTrace();
15                 }
16             }
17             System.out.println("主线程"+"["+i+"]");
18         }
19     }
20 }

下面是Java Platform SE8 API中对Thread中Join方法的解释:

public final void join(long millis)
                throws InterruptedExceptionWaits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. 
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Parameters: 
millis - the time to wait in milliseconds 
Throws: 
IllegalArgumentException - if the value of millis is negative 
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

 

posted @ 2017-01-11 16:36  易小川  阅读(466)  评论(0编辑  收藏  举报