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();
                }
            }
        }
        
    }
  • 相关阅读:
    Makefile学习
    Tmux使用
    Linux进程管理学习资料
    Linux内存管理学习资料
    Python常用的软件包
    Docker 学习
    Intel处理器技术文档
    Firefly-RK3399笔记
    Linux Kernel API
    ARM 技术文档
  • 原文地址:https://www.cnblogs.com/douyunpeng/p/13657365.html
Copyright © 2011-2022 走看看