Idle Nothing, wrote a producer consumer mode to play, by the way familiar with the use of notify.
Package Sync;public class Test {public static void main (string[] args) {test test = new test (); Producer Producer = test.new Producer ();p Roducer.start (); Consumer Consumer = Test.new Consumer (); Consumer.setname ("Consumer 0======"); Consumer.start (); Consumer consumer1 = Test.new Consumer (); Consumer1.setname ("Consumer 1======"); Consumer1.start (); Consumer consumer2 = Test.new Consumer (); Consumer2.setname ("Consumer 2======"); Consumer2.start ();} /** * @Desc Warehouse (This is an internal static class) * @author Liuxingmi * @QQ 63972012 */static class Factory {volatile int count = 0;boolean flag = True;private static Factory instance = new Factory ();p ublic static Factory getinstance () {if (instance = = null) {instance = new Factory ();} return instance;} Public synchronized void producer () {if (Count >= 5) {flag = False;this.notifyall (); try {this.wait ();} catch (Interrupt Edexception e) {e.printstacktrace ();}} count++; System.out.println ("producer count =" + count); try {thread.sleep (500);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Public synchronized void consumer () {if (!flag) {System.out.println (Thread.CurrentThread (). GetName () + "Start count =" + Count + "times:" + System.currenttimemillis ()); if (count <= 0) {try {flag = true;this.notify (); this.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} if (Count > 0) {//This place must be judged, because notify is a random wakeup thread, if not judged in a producer, multiple consumer cases will appear negative in case of count--; System.out.println (Thread.CurrentThread (). GetName () + "Count =" + count);} try {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} /** * @Desc producer * @author Liuxingmi * @QQ 63972012 */class Producer extends Thread {Factory Factory = factory.getinstance ( ); @Overridepublic void Run () {while (true) {Factory.producer ()}}} /** * @Desc Consumer * @author Liuxingmi * @QQ 63972012 */class Consumer extends Thread {Factory Factory = factory.getinstance ( ); @Overridepublic void Run () {while (true) {Factory.consumer ()}}}}
Multithreaded producer consumer model