java生产者消费者模型到精通_java生产者消费者模型
发布日期:2021-06-24 11:21:43 浏览次数:5 分类:技术文章

本文共 1395 字,大约阅读时间需要 4 分钟。

多线程: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();

}

}

转载地址:https://blog.csdn.net/weixin_32467749/article/details/114561066 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java 执行 awk_3.1 biostar lesson3 linux学习日记;java版本;awk
下一篇:java怎样将日期本土化_Java中的日期操作

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年03月29日 10时33分43秒