I. Description of the problem
The problem of producer consumers is a typical thread synchronization problem. Producers of goods placed in containers, containers have a certain capacity (can only be put in order, first put after the take), consumer goods, when the container is full, producers wait, when the container is empty, consumers wait. When the producer puts the goods into the container, informs the consumer, when the consumer takes away the goods, informs the producer.
Ii. Solutions
Locks the container resource, and when the lock is acquired, the mutex can be manipulated.
Copy Code code as follows:
public class Producerconsumertest {
public static void Main (String []args) {
Container con = new Container ();
Producer p = new Producer (con);
Consumer C = new Consumer (con);
New Thread (P). Start ();
New Thread (c). Start ();
}
}
Class goods{
int id;
Public goods (int id) {
This.id=id;
}
Public String toString () {
Return "commodity" +this.id;
}
}
Class container{//containers using stacks, advanced out
private int index = 0;
goods[] goods = new GOODS[6];
Public synchronized void push (goods good) {
while (index==goods.length) {//When container is full, producer waits
try {
Wait ();
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
Goods[index]=good;
index++;
Notifyall ()////////////////////
}
Public synchronized goods Pop () {
while (index==0) {//when there is no merchandise in the container is waiting for
try {
Wait ();
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
index--;
Notifyall ()////////////////////when consumer
return Goods[index];
}
}
Class Producer implements runnable{
Container con = new Container ();
Public Producer (Container con) {
This.con=con;
}
public void Run () {
for (int i=0; i<20; i++) {
Goods good = new Goods (i);
Con.push (good);
System.out.println ("produced:" +good);
try {
Thread.Sleep (100);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
Class Consumer implements runnable{
Container con = new Container ();
Public Consumer (Container con) {
This.con=con;
}
public void Run () {
for (int i=0; i<20; i++) {
Goods Good=con.pop ();
System.out.println ("Consumption:" +good);
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}