zoukankan      html  css  js  c++  java
  • 2020年9月12日 生产者与消费者问题

    package com.guigu.test14;
    
    public class Test14 {
        public static void main(String[] args) {
            FoodTable f = new FoodTable();
            Cook c = new Cook("厨子",f);
            Waiter w = new Waiter("服务员", f);
            
            c.start();
            w.start();
        }
    }
    class FoodTable{
        private static final int MAX = 3;
        private int count;
        
        public synchronized void put(){
            if(count>=MAX){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count++;
            System.out.println(Thread.currentThread().getName()+"放了一盘菜,剩余:" + count);
            this.notify();    
        }
        public synchronized void take(){
            if(count<=0){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count--;
            System.out.println(Thread.currentThread().getName()+"取走一盘菜,剩余:" + count);
            this.notify();
        }
        
    }
    class Cook extends Thread{
        private FoodTable f;
        
        public Cook(String name, FoodTable f) {
            super(name);
            this.f = f;
        }
    
        @Override
        public void run() {
            while(true){
                f.put();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
    class Waiter extends Thread{
        private FoodTable f;
        
        public Waiter(String name, FoodTable f) {
            super(name);
            this.f = f;
        }
    
        @Override
        public void run() {
            while(true){
                f.take();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
  • 相关阅读:
    MVAPICH
    sql server触发器的例子
    Sql Server 判断表或数据库是否存在
    JS验证用户真实姓名
    js实现瀑布流的一种简单方法实例分享
    C#实现登录窗口(不用隐藏)
    判断滚动条到底部的JS代码
    php 中文字符串首字母的获取函数
    C#获取当前页面的URL
    C#动态生成图书信息XML文件
  • 原文地址:https://www.cnblogs.com/douyunpeng/p/13657365.html
Copyright © 2011-2022 走看看