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