多线程编程<二>
wait()与notify():
1 public class ThreadComDemo { 2 public static void main(String[] args) { 3 try { 4 SyncOb sObj= new SyncOb(); 5 6 new MyThread("MyThread", sObj); 7 8 for (int i = 0; i < 10; i++) { 9 Thread.sleep(250); 10 System.out.print("."); 11 } 12 System.out.println(); 13 14 sObj.goAhead(); 15 } catch (InterruptedException e) { 16 System.out.println("Main thread interrupted."); 17 } 18 } 19 } 20 21 22 class MyThread implements Runnable { 23 SyncOb syncOb; 24 25 public MyThread( String name, SyncOb so) { 26 syncOb = so; 27 new Thread(this, name).start(); 28 } 29 30 @Override 31 public void run() { 32 syncOb.waitFor();\\线程睡眠 33 } 34 } 35 36 class SyncOb { 37 boolean ready = false; 38 synchronized void waitFor() { 39 String thrdName = Thread.currentThread().getName(); 40 System.out.println(thrdName + " is entering waitFor()."); 41 42 System.out.println(thrdName + " calling wait() to wait for " + "notification to proceed.\n"); 43 44 //调用wait()方法,这会使线程睡眠,并且会释放该对象的监视器。这样就允许另一个线程使用对象。 45 //在另一个线程进去同一个监视器并调用notify()之后,睡眠的线程会被唤醒。 46 try { 47 while(!ready) wait();//此处用的是while循环,而不是if.防止假唤醒。 48 } catch (InterruptedException e) { 49 System.out.println("Interrupted"); 50 } 51 System.out.println(thrdName + " received notification and is" + " resuming execution."); 52 } 53 54 synchronized void goAhead() { 55 String thrdName = Thread.currentThread().getName(); 56 System.out.println("\n" + thrdName + " thread calling notify() inside goAhead().\n" + 57 "This will let MyThread resume execution.\n"); 58 ready = true; 59 notify(); 60 } 61 62 }