Java - wait()/notify()

 

1、wait()惯用法:wait()包装在一个while语句中,因为某个其他任务可能会在WaitPerson被唤醒时,会突然插足并拿走订单;

2、只能在同步控制方法或同步控制块里调用wait()、notify()和notifyAll();

复制代码
import java.util.concurrent.*;

public class Meal {
        private final int orderNum;
        public Meal(int orderNum){
            this.orderNum=orderNum;
        }
        public String toString(){
            return "Meal "+orderNum;
        }
}

public class Restaurant {
    Meal meal;
    ExecutorService exec=Executors.newCachedThreadPool();
    WaitPerson waitPerson=new WaitPerson(this);
    Chef chef=new Chef(this);
    
    public Restaurant(){
        exec.execute(waitPerson);
        exec.execute(chef);
    }
}

public class WaitPerson implements Runnable{

    private Restaurant restaurant;
    public  WaitPerson(Restaurant r) {
        restaurant=r;
    }
    
    @Override
    public void run() {
        try{
            while(!Thread.interrupted()){
                synchronized (this) {
                    while(restaurant.meal==null){
                        wait(); // for the chef to produce a meal
                    }
                }
                System.out.println("WaitPerson got "+restaurant.meal);
                
                synchronized(restaurant.chef){
                    restaurant.meal=null;
                    restaurant.chef.notifyAll(); 
                }
            }
        }catch(InterruptedException e){
            System.out.println("WaitPerson interrupted");
        }    
    }
}

public class Chef implements Runnable {

    private Restaurant restaurant;
    private int count=0;
    public Chef(Restaurant r){
        restaurant=r;
    }
    
    @Override
    public void run() {
        try{
            while(!Thread.interrupted()){
                synchronized(this){
                    while(restaurant.meal!=null){
                        wait();
                    }
                }
                
                if(++count==10){
                    System.out.println("Out of food.closing");
                    restaurant.exec.shutdownNow();
                }
                
                System.out.print("Order up! ");
                
                synchronized(restaurant.waitPerson){
                    restaurant.meal=new Meal(count);
                    restaurant.waitPerson.notifyAll();
                }
                
                //TimeUnit.MILLISECONDS.sleep(100);
            }
        }catch(InterruptedException e){
            System.out.println("Chef interrupted");
        }
    }
}
复制代码

 

posted @   chenyizh  阅读(190)  评论(0编辑  收藏  举报
编辑推荐:
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
阅读排行:
· Sdcb Chats 技术博客:数据库 ID 选型的曲折之路 - 从 Guid 到自增 ID,再到
· 语音处理 开源项目 EchoSharp
· 《HelloGitHub》第 106 期
· mysql8.0无备份通过idb文件恢复数据过程、idb文件修复和tablespace id不一致处
· 使用 Dify + LLM 构建精确任务处理应用
点击右上角即可分享
微信分享提示