熟悉生產者消費者模型是學習多線程的編程的必經之路,它廣泛應用於各種系統中,如TCP消息隊列等。下面是模擬實現的代碼(爲什麼叫模擬,請看<二>真實實現就懂了)。
Store.java
package test.producerAndConsumer1;
/**
* 倉庫類
* create by qiuping.wu on 2015-08-10
*/
public class Store {
private int count = 0;
private final int MAX_NUM = 10;
public void Produce() {
while (count >= MAX_NUM) {
System.out.println(Thread.currentThread().getName()+"FFFFFFFFFFFFFFFFFFFFFFFF隊列滿");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (this) {
count++;
System.out.println(Thread.currentThread().getName()+"++++++++++生產者往倉庫放入一件商品,count=" + count);
}
}
public void Consume() {
while (count <= 0) {
System.out.println(Thread.currentThread().getName()+"00000000000隊列空");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (this) {
count--;
System.out.println(Thread.currentThread().getName()+"---------------消費者取出一件商品,count=" + count);
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Store store = new Store();
store.Produce();
store.Produce();
store.Consume();
store.Consume();
store.Consume();
}
}
package test.producerAndConsumer1;
/**
* 生產者類
* create by qiuping.wu on 2015-08-10
*/
public class Producer implements Runnable {
private Store store;
public Producer(Store store) {
this.store = store;
}
@Override
public void run()
{
while(true)
{
store.Produce();
try {
Thread.sleep(900);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Consumer.java
package test.producerAndConsumer1;
/**
* 消費者類
* create by qiuping.wu on 2015-08-10
*/
public class Consumer implements Runnable {
private Store store;
public Consumer(Store store) {
this.store = store;
}
@Override
public void run() {
while (true) {
store.Consume();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
測試一:生產者:消費者= 1:1
testSingle.java
package test.producerAndConsumer1;
/**
* 單生產者單消費者測試類
* create by qiuping.wu on 2015-08-10
*/
public class testSingle {
public static void main(String[] args) {
Store store = new Store();
Producer p = new Producer(store);
Consumer c = new Consumer(store);
new Thread(p).start();
new Thread(c).start();
}
}
測試二:生產者:消費者= m:n
testMulti.java
package test.producerAndConsumer1;
/**
* 多生產者多消費者測試類
* create by qiuping.wu on 2015-08-10
*/
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class testMulti {
public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
Store store = new Store();
Producer p = new Producer(store);
Consumer c = new Consumer(store);
for (int i = 0; i < 3; i++) {
es.submit(p);
}
for (int i = 0; i < 4; i++) {
es.submit(c);
}
}
}