Java:Thread:join()方法加入一个线程
在Java多线程中,如果某一个线程s在另一个线程t上调用t.join(),此线程s将被挂起,直到目标线程t结束才恢复(此时t.isAlive()返回为假)。
也可以在调用join()时带上一个超时参数(单位可以是毫秒,或者毫秒和纳秒),这样如果目标线程在这段时间内还没有结束的话,join()方法总能返回。
对join()方法的调用可以被中断,做法是在调用线程上调用interrupt()方法。
1 class Sleeper extends Thread { 2 3 private int duration; 4 5 public Sleeper(String name, int sleepTime) { 6 super(name); 7 this.duration = sleepTime; 8 start(); 9 } 10 11 @Override 12 public void run() { 13 try { 14 sleep(duration); 15 } catch (InterruptedException e) { 16 /** 异常被捕获时将清理线程的中断标识,因此在catch子句中isInterrupted()返回的值为false.*/ 17 System.out.println(getName() + "was interrupted. " + "isInterrupted(): " + isInterrupted()); 18 return ; 19 } 20 System.out.println(getName() + " has awakened."); 21 } 22 23 } 24 25 26 class Joiner extends Thread { 27 28 private Sleeper sleeper; 29 30 public Joiner(String name, Sleeper sleeper) { 31 super(name); 32 this.sleeper = sleeper; 33 start(); 34 } 35 36 @Override 37 public void run() { 38 try { 39 sleeper.join(); 40 } catch (InterruptedException e) { 41 System.out.println("Interrupted."); 42 } 43 System.out.println(getName() + " join completed"); 44 } 45 46 } 47 48 49 public class JoinDemo { 50 51 public static void main(String[] args) { 52 Sleeper 53 sleepy = new Sleeper("Sleepy", 1500), 54 grumpy = new Sleeper("Grumpy", 1500); 55 Joiner 56 dopey = new Joiner("Dopey", sleepy), 57 doc = new Joiner("Doc", grumpy); 58 grumpy.interrupt(); 59 } 60 61 } 62 63 /** 64 * 程序运行结果: 65 * Grumpywas interrupted. isInterrupted(): false 66 * Doc join completed 67 * Sleepy has awakened. 68 * Dopey join completed 69 * 70 */