熟悉生产者消费者模型是学习多线程的编程的必经之路,它广泛应用于各种系统中,如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);
}
}
}