让两个线程顺序执行
1 public class ThreadJoiner { 2 public static void main(String[] args) { 3 Object lock = new Object(); 4 5 Thread starterThread = new Thread(new StarterThread(lock)); 6 Thread enderThread = new Thread(new EnderThread(lock)); 7 8 starterThread.start(); 9 enderThread.start(); 10 } 11 } 12 class StarterThread implements Runnable { 13 14 private Object lock = null; 15 16 public StarterThread(Object lock) { 17 this.lock = lock; 18 } 19 20 public void run() { 21 System.out.println("start.."); 22 23 for(int i =0; i<10; i++){ 24 System.out.println("start:"+i); 25 } 26 synchronized(lock){ 27 lock.notifyAll(); 28 } 29 } 30 } 31 class EnderThread implements Runnable { 32 private Object lock = null; 33 public EnderThread(Object lock) { 34 this.lock = lock; 35 } 36 37 public void run() { 38 synchronized(lock){ 39 try { 40 lock.wait(); 41 } catch (InterruptedException e) { 42 e.printStackTrace(); 43 } 44 } 45 System.out.println("end.."); 46 for(int i =0; i<10; i++){ 47 System.out.println("end:"+i); 48 } 49 } 50 } 51 /* 52 start.. 53 start:0 54 start:1 55 start:2 56 start:3 57 start:4 58 start:5 59 start:6 60 start:7 61 start:8 62 start:9 63 end.. 64 end:0 65 end:1 66 end:2 67 end:3 68 end:4 69 end:5 70 end:6 71 end:7 72 end:8 73 end:9 74 */