Thread:线程之间的通信,使用wait()和notify()
没有使用wait()和notify()
package com.David; class Q{ int n; synchronized int get(){ System.out.println( " Got: " + n); return n; } synchronized void put( int n){ this .n = n; System.out.println( " Put: " + n); }} class Producer implements Runnable{ Q q; Producer(Q q){ this .q = q; new Thread( this , " Producer " ).start(); } public void run(){ int i = 0 ; while (i < 10 ){ q.put(i ++ ); } }} class Consumer implements Runnable{ Q q; Consumer(Q q){ this .q = q; new Thread( this , " Consumer " ).start(); } public void run(){ int i = 0 ; while (i ++< 10 ){ q.get(); } }} public class MyTest { public static void main(String[] args) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println( " Press Control-C to stop. " ); }}输出结果是:
Put:0Put:1Put:2Put:3Put:4Put:5Put:6Put:7Put:8Put:9Press Control-C to stop.Got:9Got:9Got:9Got:9Got:9
使用了wait()和notify()后
package com.David; class Basic{ private int n = 0 ; private boolean valueSet = false ; synchronized public int get(){ if ( ! valueSet){ try { wait(); } catch (Exception ex){ ex.printStackTrace(); } } System.out.println( " Got: " + n); valueSet = false ; notify(); return n; } synchronized public void put( int n){ if (valueSet){ try { wait(); } catch (Exception ex){ ex.printStackTrace(); } } this .n = n; valueSet = true ; System.out.println( " Put: " + n); notify(); }} class GotNum implements Runnable{ Basic b; GotNum(Basic b){ this .b = b; new Thread( this ).start(); } public void run(){ int i = 0 ; while (i ++< 10 ){ b.get(); } }} class PutNum implements Runnable{ Basic b; PutNum(Basic b){ this .b = b; new Thread( this ).start(); } public void run(){ int i = 0 ; while (i < 10 ){ b.put(i ++ ); } }} public class MMText { /** * @param args */ public static void main(String[] args) { Basic b = new Basic(); new PutNum(b); new GotNum(b); }}输出结果:
Put:0Got:0Put:1Got:1Put:2Got:2Put:3Got:3Put:4Got:4Put:5Got:5Put:6Got:6Put:7Got:7Put:8Got:8Put:9Got:9