博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java生产者消费者模型到精通_java生产者消费者模型
阅读量:1533 次
发布时间:2019-04-21

本文共 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();

}

}

转载地址:http://dlkdy.baihongyu.com/

你可能感兴趣的文章
【Scratch考级99图】图23-绘制复杂图形
查看>>
scratch森林的一天 电子学会图形化scratch编程等级考试一级真题编程题答案2020-9
查看>>
web渗透--4--自动化漏洞扫描
查看>>
CTF_EXP04:2017 赛客夏令营 Web-random
查看>>
CTF_EXP02:XCTF PHP2
查看>>
CTF_EXP03: [SUCTF 2019] EasySQL
查看>>
BUUCTF [极客大挑战 2019] BuyFlag
查看>>
BUUCTF [极客大挑战 2019] Secret File
查看>>
ubuntu定时任务cron 访问网址php
查看>>
php 获取顶级域名、一级域名
查看>>
php7 $GLOBALS['HTTP_RAW_POST_DATA']接收不到值
查看>>
Thinkphp if标签不支持3层以上嵌套
查看>>
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
查看>>
又一软件巨头倒下,原因竟然是...
查看>>
Mybatis系列之自定义SQL拦截器
查看>>
tomcat系列之编译超过64k大小的jsp文件报错原因
查看>>
设计模式之职责链模式(行为型)
查看>>
设计模式之状态模式(行为型)
查看>>
Oracle应用之开窗函数笔记及应用场景
查看>>
Java应用之传参乱码问题解决方法
查看>>