Java multi-threading and producers of consumer issues:
com.test Package; class the Message { Private String title; Private Content String; // representation of production and consumption, flag = true, allows the production, consumption is not allowed; flag = false, do not allow the production, consumption allows private boolean flag; // use synchronized solve synchronization problems, ensure consistent data public synchronized void the SET (String title, String Content) { IF (this.flag == to true) {// unable to produce, waiting to be consumed the try { super.wait () ; } the catch (InterruptedException E) { e.printStackTrace (); } } this.title = title; the try { the Thread.sleep (100); } the catch (InterruptedException E) { e.printStackTrace (); } this.content = Content; this.flag = to true; // has produced a super.notify (); // wake up threads waiting } public String the synchronized GET () { IF (this.flag == false) {// production has not need to wait for the try { super.wait (); } the catch (InterruptedException E) { e.printStackTrace (); } } the try { the Thread.sleep (100); } the catch (InterruptedException E ) { e.printStackTrace (); } the try { return this.title + "=" + this.content; } {the finally this.flag = to false; // continue production super.notify (); // wait thread wakeup } } } class Producer implements Runnable{ private Message msg; public Producer(Message msg){ this.msg=msg; } @Override public void run() { for(int x=0;x<10;x++){ if(x%2==0){ this.msg.set("0","0"); }else { this.msg.set("1","1"); } } } } class Consumer implements Runnable{ private Message msg; public Consumer(Message msg){ this.msg=msg; } @Override RUN void public () { for (int X = 0; X <10; X ++) { System.out.println (this.msg.get ()); } } } public class MultithreadingDemo { public static void main (String [] args) throws Exception { the Message the Message MSG = new new (); new new the thread (new new producer (MSG).) start (); // start producer thread new thread (new Consumer (msg) ) start ();. // start consumer thread } }