`

Java实现生产者消费者模式

 
阅读更多

package com.ubs.joe.demo;

public class ProductThread implements Runnable{
    private Count count;
    public ProductThread(Count count){
        this.count = count;
    }
    public void run(){
        while(true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count.incrementCount();
        }
    }
    
    public static void main(String [] args){
        Count count = new Count();
        ProductThread d = new ProductThread(count);
        CustomerThread r = new CustomerThread(count);
        Thread t1 = new Thread(d);
        Thread t2 = new Thread(r);
        Thread t3 = new Thread(d);
        Thread t4 = new Thread(r);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class CustomerThread implements Runnable{
    private Count count;
    public CustomerThread(Count count){
        this.count = count;
    }
    public void run(){
        while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count.decrementCount();    

        }
    }
}

class Count{
    int count = 0;
    int flag = 0;
    public synchronized void incrementCount(){
        while(flag!=0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count++;
        System.out.println(count);
        if(count==20){
            flag = 1;
            notifyAll();
        }
    }
    
    public synchronized void decrementCount(){
        while(flag==0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        System.out.println(count);
        if(count==0){
            flag = 0;
            notifyAll();
        }
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics