The realization of the classic consumer and producer:
Precautions:
1: Use Wait () in the loop, because when the thread obtains the lock, it is possible that other conditions are not met:
2: The common buffer pool is to be used with the lock mechanism:
1 Packagedemo;2 3 ImportJava.util.Vector;4 5 Public classMain {6 7 Public Static voidMain (string[] args) {8Vector<integer> pool=NewVector<integer>();9Producer producer=NewProducer (Pool, 4);TenConsumer consumer=NewConsumer (pool); One NewThread (producer). Start (); A NewThread (consumer). Start (); - } - the } - - //producers - classProducerImplementsrunnable{ + PrivateVector Pool; - PrivateInteger size; + A PublicProducer (Vector pool, Integer size) { at This. Pool =Pool; - This. Size =size; - } - @Override - Public voidrun () { - for(inti=0;i<7;i++){ in Try { -SYSTEM.OUT.PRINTLN ("Produce" +i); to Produce (i); +}Catch(interruptedexception e) { - //TODO auto-generated Catch block the e.printstacktrace (); * } $ }Panax Notoginseng } - Private voidProduce (intIthrowsinterruptedexception{ the while(pool.size () = =size) { + synchronized(pool) { ASystem.out.println ("Pool is full Producer are waiting,size is" +pool.size ()); the pool.wait (); + } - } $ synchronized(pool) { $ Pool.add (i); - Pool.notifyall (); - } the } - }Wuyi the - //Consumer Wu classConsumerImplementsrunnable{ - PrivateVector Pool; About PublicConsumer (Vector pool) { $ This. Pool =Pool; - } - - @Override A Public voidrun () { + for(inti=0;i<7;i++){ the Try { -System.out.println ("Consume" +i); $ consume (); the}Catch(interruptedexception e) { the //TODO auto-generated Catch block the e.printstacktrace (); the } - } in } the the Private voidConsume ()throwsinterruptedexception{ About while(Pool.isempty ()) { the synchronized(pool) { theSystem.out.println ("Pool is empty Consumer was Waiting,size is" +pool.size ()); the pool.wait (); + } - } the synchronized(pool) {Bayi Pool.notifyall (); thePool.remove (0); the - } - } the}
The execution results are:
java--using wait and notify for producers and consumers