生产者消费者程序练手

Posted vanpersie_9987

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生产者消费者程序练手相关的知识,希望对你有一定的参考价值。

写一段生产者、消费者的程序:

//资源
class Meal 
    private final int orderNum;
    public Meal(int orderNum)  
        this.orderNum = orderNum;
    
    @Override
    public String toString() 
        return "Meal " + orderNum;
    



//服务生 消费者
class WaitPerson implements Runnable 
    private Restaurant restaurant;
    public WaitPerson(Restaurant restaurant) 
        this.restaurant = restaurant;
    
    @Override
    public void run() 
        try 
            while(!Thread.interrupted()) 
                synchronized(this) 
                    while(restaurant.meal == null) 
                        this.wait();
                    
                
                System.out.println("WaitPerson got " + restaurant.meal);
                synchronized(restaurant.chef) 
                    restaurant.meal = null;
                    restaurant.chef.notify();
                
            
         catch(InterruptedException e) 
            System.out.println("WaitPerson Interrupted");
        
    



//厨师 生产者
class Chef implements Runnable 
    private int count = 0; 
    private Restaurant restaurant;
    public Chef(Restaurant restaurant) 
        this.restaurant = restaurant;
    
    @Override
    public void run() 
        try 
            while(!Thread.interrupted()) 
                synchronized(this) 
                    while(restaurant.meal != null) 
                        this.wait();
                    
                
                if(++count == 10) 
                    System.out.println("System Quit");
                    restaurant.exec.shutdownNow();
                    System.exit(0);
                
                System.out.print("Order up! ");
                synchronized(restaurant.waitPerson) 
                    restaurant.meal = new Meal(count);
                    restaurant.waitPerson.notify();
                
                TimeUnit.MILLISECONDS.sleep(100);
            
         catch(InterruptedException e) 
            System.out.print("Chef Interrupted");
        
    



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

    
    public static void main(String[] args) 
        new Reataurant();
    

看看哪有错。。。应该没错

以上是关于生产者消费者程序练手的主要内容,如果未能解决你的问题,请参考以下文章

wait/notify实现生产者-消费者模型,join方法

Java生产消费模型—ArrayBlockingQueue详解

java生产者与消费者模式

python生产者消费者模型

生产者消费者模型实现多线程异步交互

生产者消费者模型----------基于多进程多线程单线程并发