package thread;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by renren on 16/8/10.
*/
public class ProducerAndConsumer {
static class Storage{///仓库
int storageCount;
public static final int MAX = 100;
public synchronized void produce(){
if (storageCount==MAX){
System.out.println(storageCount+"仓库已经满");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storageCount++;
System.out.println(storageCount+"生产产品");
notify();
}
public synchronized void consume(){
if (storageCount == 0){
System.out.println(storageCount+"仓库已经空");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storageCount--;
System.out.println(storageCount+"消费产品");
notify();
}
}
static class Producer implements Runnable{
Storage mStorage;
public Producer(Storage mStorage) {
this.mStorage = mStorage;
}
@Override
public void run() {
while (true)
mStorage.produce();
}
}
static class Consumer implements Runnable{
Storage mStorage;
public Consumer(Storage mStorage) {
this.mStorage = mStorage;
}
@Override
public void run() {
while (true)
mStorage.consume();
}
}
public static void main(String []args){
Storage mStorage = new Storage();
ExecutorService exe = Executors.newCachedThreadPool();
exe.execute(new Producer(mStorage));
exe.execute(new Consumer(mStorage));
exe.shutdown();
}
}
Java 实现生产者与消费者
最新推荐文章于 2019-06-27 20:23:08 发布