java生产者消费者模型

多线程:sleep(),线程处于就绪状态,CPU执行其他线程,该线程的监控状态依然保持着,且不会释放对象锁。notify()线程会放弃对象锁。

class Meal {

private final int orderNum;


public Meal(int orderNum){

this.orderNum = orderNum;

}

}

class WaitPeople implements Runnable {

private Restaurant restaurant;

public void run() {

try{

while(!Thread.interrupted()){

synchronized(this){

while(restaurant.meal == null){

wait();

}

System.out.println("wait people got " + restaurant.meal);

synchronized(restaurant.chef) {

restaurant.meal = null;

restarurant.chef.notifyAll();

}

}

}

}catch(InterrupedException e) {

System.out.println("Wait person interrupted");

}

}

}


class Chef implements Runnable {

private Restaurant restaurant;

private int count = 0;

public Chef(Restarurant restaurant){

this.restaurant = restaurant;

}

public void run(){

try{

synchronized(this){

while(!Thread.interupted()){

wait();

}

if(++ count == 10){

restaurant.exec.showdownNow();

}

System.out.println("order up"):

synchronized(restaurant.waitpeople){

restaurant.mean = new Meal(count);

restaurant.waitpeople.notifyAll();

}

}

TimeUnit.MILLISECONDS.sleep(100);

}catch(InterruptedException e){

}

}

}


public class Restaurant {

Meal meal;

ExecutorService exec = Exectors.newCachedThreadPool();

Chef chef = new Chef(this);

WaitPerson waitpeople = new WaitPerson(this):

public Restaurant(){

exec.execute(chef);

exec.execute(waitpeople);

}

public static void main(String[] args){

new Restaurant();

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值