public class clerk {private int product=0;//Products By default 0;//producer-generated products to the clerk public Synchronized void addproduct () {if (this.product>=20) {try {wait ();//product is full, please wait in production} catch (interruptedexception e) {// TODO Auto-generated catch block E.printstacktrace ();}} else{product++; System.out.println ("Producer Production Place" +product+ "product". Notifyall (); //notify the consumer of the waiting area to take the product today}}//the consumer to fetch the product from the Clerk public synchronized void getproduct () {if ( this.product<=0) {try {wait ();//product is not in stock, please wait to take} catch (interruptedexception e) {// TODO Auto-generated catch block E.printstacktrace ();}} Else{system.out.println ("Consumer took the first" +product+ "Product");p Roduct--;notifyall ();//Notification waiting area generator can produce product}}}// The task to be performed by the consumer thread public class consumer implements runnable {private clerk cl; public consumer (CLERK&NBSP;CL) {this.cl=cl;} public void run () {system.out.println ("Consumer OpenStart to take away the product! "); while (true) {try {thread.sleep ((int) (Math.random () *10) *100);} catch (interruptedexception e) {// TODO Auto-generated catch Block E.printstacktrace ();} Cl.getproduct ();//Take Away Product}}}
/*
* Producer and consumer issues
*
* Producers say products to the power supply, and consumers out of the shop staff out of the product, the clerk can only hold a fixed number of products at a time,
* If the producer produces too much product, the clerk will call the producer to wait, if there is a vacancy in the store to inform the producer to continue production;
* If there is no product in the shop, the clerk will tell the consumer to wait, if there is a product in the store and then notify consumers to take away the product.
Problem
* Producers faster than consumers are, consumers will miss out some of the data did not take
* Consumers will take the same data when the consumer is faster than the producer
*
*/
public class Demo {
}
public class Main {
public static void Main (string[] args) {
TODO auto-generated method stubs
Clerk cl=new Clerk ();
Thread Prt=new Thread (new Producer (CL));//producer Thread
Thread Cot=new Thread (new Consumer (CL));//Consumer thread
Prt.start ();
Cot.start ();
}
}
Java CEO-java Multithreading