java Java实现的生产者和消费者问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Java实现的生产者和消费者问题相关的知识,希望对你有一定的参考价值。
import java.util.concurrent.*;
public class Restaurant {
Meal meal;
ExecutorService exec = Executors.newCachedThreadPool();
WaitPerson waitPerson = new WaitPerson(this);
Chef chef = new Chef(this);
public Restaurant() {
exec.execute(chef);
exec.execute(waitPerson);
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
new Restaurant();
}
}
interface StupidPrint {
default void print(String s) {
System.out.print(s+" ");
}
default void printnb(String s) {
System.out.println(s);
}
}
class Meal implements StupidPrint {
private final int orderNum;
public Meal(int orderNum) {
this.orderNum = orderNum;
}
public String toString() {
return "Meal " + orderNum;
}
}
class WaitPerson implements Runnable, StupidPrint {
private Restaurant restaurant;
public WaitPerson(Restaurant r) {
restaurant = r;
}
public void run() {
try {
while (!Thread.interrupted()) {
synchronized (this) {
while (restaurant.meal == null) wait();
}
print("Waitperson got " + restaurant.meal);
synchronized (restaurant.chef) {
restaurant.meal = null;
restaurant.chef.notifyAll();
}
}
} catch (InterruptedException e) {
print("WaitPerson interrupted");
}
}
}
class Chef implements Runnable, StupidPrint {
private Restaurant restaurant;
private int count = 0;
public Chef(Restaurant r) {
restaurant = r;
}
public void run() {
try {
while (!Thread.interrupted()) {
synchronized (this) {
while (restaurant.meal != null) wait();
}
if (++count == 10) {
printnb("Out of food, closing");
restaurant.exec.shutdownNow();
TimeUnit.MILLISECONDS.sleep(100); // in order to show the message of Chef interrupted
}
printnb("Order up! ");
synchronized (restaurant.waitPerson) {
restaurant.meal = new Meal(count);
restaurant.waitPerson.notifyAll();
}
TimeUnit.MILLISECONDS.sleep(100);
}
} catch (InterruptedException e) {
print("Chef interrupted");
}
}
}
以上是关于java Java实现的生产者和消费者问题的主要内容,如果未能解决你的问题,请参考以下文章