public class Clerk {
private int product=0;//product default 0;
The product produced by the producer is given to the clerk
Public synchronized void Addproduct () {
if (this.product>=20) {
try {
Wait ();//product is full, please wait in the production
} catch (Interruptedexception e) {
TODO Auto-generated catch block
E.printstacktrace ();
}
}else{
product++;
System.out.println ("Producer Production Place" +product+ "product". ");
Notifyall (); Notify consumers in the waiting area to pick up the product today
}
}
Consumers take products from shop assistants
Public synchronized void GetProduct () {
if (this.product<=0) {
try {
Wait ();//product is not in stock, please wait for a second to take
} catch (Interruptedexception e) {
TODO Auto-generated catch block
E.printstacktrace ();
}
}else{
System.out.println ("The consumer has taken the first" +product+ "Product");
product--;
Notifyall ();//notify the generator of the waiting area to produce the product
}
}
}
Tasks to be performed by consumer threads
public class Consumer implements Runnable {
Private clerk CL;
Public Consumer (Clerk cl) {
THIS.CL=CL;
}
public void Run () {
System.out.println ("The consumer starts 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 the product
}
}
}
Task to be performed by the producer thread
public class Producer implements Runnable {
Private clerk CL;
Public Producer (Clerk cl) {
THIS.CL=CL;
}
public void Run () {
System.out.println ("Producers start producing products!") ");
while (true) {
try {
Thread.Sleep ((int) (Math.random () *10) *100);
} catch (Interruptedexception e) {
TODO Auto-generated catch block
E.printstacktrace ();
}
Cl.addproduct ();//Production of products
}
}
}
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 ();
}
}
This article is from the "12156507" blog, please be sure to keep this source http://12166507.blog.51cto.com/12156507/1875372
Multi-threaded consumer and manufacturer of the Golden case!!