The producer producer, by definition, is the thread of production data, and the consumer consumer is the thread that uses the data. Can have more than one producer, can also have multiple consumers, when the producer and the consumer is a time, also known as Pipeline pipe Pattern.
Here is a simple example, a thread plus 1, a thread minus 1, a producer, a consumer, the producer to add 1, the consumer to reduce 1. The following code has verified OK.
1. Info data object, used to store data used by producers and consumers
public class Info {
private int count;
Private Boolean flag;
Public synchronized void set () {
if (flag) {
try {
Super.wait ();
} catch (Exception e) {
E.printstacktrace ();
}
}
System.out.println ("Producer INC 1---" + (++count));
try {
Thread.Sleep (100);
} catch (Exception e) {
E.printstacktrace ();
}
Flag = true;
Super.notify ();
}
Public synchronized void get () {
if (!flag) {
try {
Super.wait ();
} catch (Exception e) {
E.printstacktrace ();
}
}
System.out.println ("Consumer Dec 1---" + (--count));
try {
Thread.Sleep (100);
} catch (Exception e) {
E.printstacktrace ();
}
Flag = false;
Super.notify ();
}
}
Producer Producers:
public class Producer implements Runnable {
Private info info = null;
Public Producer (Info info) {
This.info = info;
}
@Override
public void Run () {
for (int i=0; i<20; i++) {
This.info.set ();
}
}
}
Consumer consumers:
public class Consumer implements Runnable {
Private info info = null;
Public Consumer (Info info) {
This.info = info;
}
@Override
public void Run () {
for (int i=0; i<20; i++) {
This.info.get ();
}
}
}
Testing the class test:
public class Test {
public static void Main (string[] args) {
Info info = new info ();
Producer Producer = new Producer (info);
New Thread (producer). Start ();
Consumer Consumer = new Consumer (info);
New Thread (consumer). Start ();
}
}
Java multi-thread producer (Producer) and consumer (Consumer)