以厨师和服务生为例:
/**
* 生产者与消费者问题
*/
public class Demo{
public static void main(String[] args) {
Food f = new Food();
new cook(f).start();
new waiter(f).start();
}
}
/**
* 厨师
*/
class cook extends Thread{
private Food f;
public cook(Food f){
this.f = f;
}
@Override
public void run() {
for (int i = 0 ;i<100;i++){
if (i%2==0){
f.setNameAndTaste("老干妈","辣味");
}else {
f.setNameAndTaste("小米粥","甜味");
}
}
}
}
/**
* 服务生
*/
class waiter extends Thread{
private Food f;
public waiter(Food f){
this.f = f;
}
@Override
public void run() {
for (int i = 0 ;i<100;i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
f.get();
}
}
}
/**
* 菜名
*/
class Food{
private String name;
private String taste;
private boolean flag = true;//标记是否可以生产
public synchronized void setNameAndTaste(String name,String taste) {
this.name = name;
if (flag) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.taste = taste;
flag = false;
this.notifyAll();//唤醒在this下的所有睡着的线程
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void get(){
if (!flag) {
System.out.println("菜名为:" + name + ",味道:" + taste);
flag = true;
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行结果: