Producer生產者顧名思義就是生產數據的線程,Consumer消費者就是使用數據的線程。能夠有多個生產者,也能夠有多個消費者,當生產者和消費者都是一個的時候,又叫作管道Pipe Pattern。ide
下面簡單寫了個例子,一個線程加1,一個線程減1,一個生產者、一個消費者,生產者用來加1,消費者用來減1。下面代碼已經驗證ok。測試
1. Info數據對象,用來保存生產者和消費者使用的數據this
public class Info {線程
private int count;對象
private boolean flag;ip
public synchronized void set() {get
if(flag) {it
try {io
super.wait();class
} 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生產者:
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消費者:
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();
}
}
}
測試類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();
}
}