zoukankan      html  css  js  c++  java
  • 生产者消费者问题

     思路:

    生产者判读是否大于20: 若 否,则生产一个产品并且唤醒(消费者).若是,则堵塞.

    消费者判读是否大于0,若是,则消费一个产品,并唤醒(生产者).若否,则堵塞.

    我们将生产和消费的方法,放到店员类,这样可以操作共享数据.

    package com.LearnJava.Thread;
    class Clerk {
        private int products=0;
    
        public synchronized void prodectOne(){
            if(products<20){
                products++;
                System.out.println(Thread.currentThread().getName()+"生产第"+products+"个产品");
                notifyAll();
            }else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        public synchronized void consumeOne(){
            if(products>0){
                System.out.println(Thread.currentThread().getName()+"消费第"+products+"个产品");
                products--;
                notifyAll();
            }else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class Productor extends Thread{
        private Clerk c;
        Productor(Clerk c){
            this.c=c;
        }
        @Override
        public void run() {
            while (true){
                c.prodectOne();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class Customer extends Thread{
        private Clerk c;
        Customer(Clerk c){
            this.c=c;
    
        }
        @Override
        public void run() {
            while (true){
                c.consumeOne();
    
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public class PCCProblem {
        public static void main(String[] args) {
            Clerk c = new Clerk();
            Productor p1 = new Productor(c);
            Productor p2 = new Productor(c);
            Customer c1 = new Customer(c);
            p1.start();
            p2.start();
            c1.start();
    
    
    
    
    
    
        }
    }
    View Code
  • 相关阅读:
    04-树7 二叉搜索树的操作集
    04-树6 Complete Binary Search Tree
    04-树5 Root of AVL Tree
    04-树4 是否同一棵二叉搜索树
    05-树8 File Transfer
    05-树7 堆中的路径
    二叉树的非递归遍历(先序、中序、后序和层序遍历)
    队列的定义与操作——顺序存储和链式存储
    Maven项目的核心pom.xml解释(转)
    eclipse安装插件的三种方式
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/12283995.html
Copyright © 2011-2022 走看看