日期:2014-05-20 浏览次数:20707 次
public class WaitComm { public static void main(String[] args) { WFlagSend s = new WFlagSend(); WFlagRec r = new WFlagRec(s); Thread st = new Thread(s); Thread rt = new Thread(r); rt.setDaemon(true); st.start(); rt.start(); try { st.join(); while ( s.isValid ){ Thread.sleep(100); } }catch(InterruptedException e){ e.printStackTrace(); } } } class WFlagSend implements Runnable { int theValue; boolean isValid; public void run() { for ( int i=0; i<5; i++){ synchronized(this){ while (isValid){ try{ this.wait(); }catch(Exception e){e.printStackTrace();} } } theValue = (int)(Math.random()*256); System.out.println("sending " + theValue ); synchronized(this){ isValid = true; this.notify(); } } } } class WFlagRec implements Runnable { private WFlagSend theSender; public WFlagRec(WFlagSend sender){ theSender = sender; } public void run() { while ( true ) { synchronized(theSender) { while ( !theSender.isValid ){ try{ theSender.wait(); }catch(Exception e){e.printStackTrace();} } } System.out.println("received " + theSender.theValue); synchronized(theSender) { theSender.isValid = false; theSender.notify(); } } } }
------解决方案--------------------
class Test { public static void main(String[] args) { final Arrays a = new Arrays(); Thread t1 = new Thread() { public void run() { int j=1; while(true) { a.write(j++); } } }; Thread t2 = new Thread() { public void run() { while(true) { a.read(); } } }; t1.start(); t2.start(); } } class Array { int n = 0; int[] num = new int[n]; boolean b = false; synchronized void write(int j) { int n = 0; try { if (b) { wait(); } } catch(Exception e) { System.out.println(e); } num[n++] = j; System.out.println(Thread.currentThread().getName()+" "+num[n]); b = true; notify(); } synchronized void read() { try { if(!b) { wait(); } } catch(Exception e) { System.out.println(e); } System.out.println(Thread.currentThread().getName()+" "+num[n]); b = false; notify(); } }