1 // Many threads join a single thread. 2 3 class Sleeper implements Runnable 4 { 5 int num = -1; 6 Sleeper(int num)7 public Sleeper(int num) 8 { 9 this.num = num; 10 } 11 run()12 public void run() 13 { 14 System.out.println("sleeping"); 15 try 16 { 17 Thread.sleep(500); 18 } 19 catch (InterruptedException x) 20 { 21 System.out.println("sleep() interrupted"); 22 } 23 System.out.println("done"); 24 } 25 } 26 27 class Joiner implements Runnable 28 { 29 Thread join_target; 30 Joiner(Thread t)31 public Joiner(Thread t) 32 { 33 this.join_target = t; 34 } 35 run()36 public void run() 37 { 38 try 39 { 40 long start = System.currentTimeMillis(); 41 join_target.join(2000); 42 if ((System.currentTimeMillis() - start) > 1900) 43 System.out.println("Error: Join timed out"); 44 else 45 System.out.println("ok"); 46 } 47 catch (InterruptedException x) 48 { 49 System.out.println("join() interrupted"); 50 } 51 } 52 53 } 54 55 public class Thread_Join 56 { main(String[] args)57 public static void main(String[] args) 58 { 59 Thread primary = new Thread(new Sleeper(1)); 60 primary.start(); 61 for (int i=0; i < 10; i++) 62 { 63 Thread t = new Thread(new Joiner(primary)); 64 t.start(); 65 } 66 } 67 } 68