//: FlagComm.java public class FlagComm { public static void main(String[] args) { FlagSend s = new FlagSend(); FlagRec r = new FlagRec(s); Thread st = new Thread(s); Thread rt = new Thread(r); rt.setDaemon(true); st.start(); rt.start(); try { st.join(); // for Windows while ( s.isValid ) { Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } class FlagSend implements Runnable { volatile int theValue; volatile boolean isValid; public void run() { for ( int i=0; i<5; i++ ) { while ( isValid ) { Thread.yield(); } theValue = (int)(Math.random()*256); System.out.println("sending "+theValue); isValid = true; } } } class FlagRec implements Runnable { FlagSend theSender; public FlagRec(FlagSend sender) { theSender = sender; } public void run() { while ( true ) { while ( !theSender.isValid ) { Thread.yield(); } System.out.println("received "+theSender.theValue); theSender.isValid = false; } } }