您的位置:首页 > 其它

一个生产者和一个消费者

2006-12-21 18:09 295 查看
我想开发一个可以允许最多有3个物品的        生产者 消费者 例子 
说明的是生产者,消费者都只有一个

1。代表商店店员

public class Clerk {
   
    private int product = 0; 
 
 ////////////////////////
 ///////////////////////
    // 这个方法是由Producer调用
 ///////////////////////
 //////////////////////

    public synchronized void setProduct() {
        if(this.product>=3) {
            try {
                // 店里货价已经慢了,請稍候!
                wait();
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
 
        this.product++;
        System.out.printf("现在共有商品 (%d)%n个", this.product);

        // 通知等待區中的一個消費者可以繼續买商品了
        notify();
    }
   
    // 這個方法由Consumer调用

    public synchronized int getProduct() {
        if(this.product<=0) {
            try {
                // 货价空了,請稍候!
                wait();
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
 
        this.product--;
        System.out.printf(
                  "现在还剩下商品 (%d)%n个", this.product);
 
        // 通知等待區中的一個生產者可以繼續生产商品
        notify();
      
        return this.product;
    }
}

 

2。生产者

public class Producer implements Runnable {
    private Clerk clerk;
   
    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }
   
    public void run() {
        System.out.println(
                "生產者開始生產整數......");

        // 生產1到10的整數
        for(int product = 1; product <= 10; product++) {
            try {
                // 暫停隨機時間
                Thread.sleep((int) Math.random() * 3000);
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }
            // 將產品交給店員
            clerk.setProduct();
        }      
    }
}

 

3。消费者

public class Consumer implements Runnable {
    private Clerk clerk;
   
    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }
   
    public void run() {
        System.out.println(
                "消費者開始消耗整數......");

        // 消耗10個整數
        for(int i = 1; i <= 10; i++) {
            try {
                // 等待隨機時間
                Thread.sleep((int) (Math.random() * 3000));
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }

            // 從店員處取走整數
            clerk.getProduct();
        }
    }
 }

 

4。main调用程序

public class ProduceConsumerDemo {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
 
        Thread producerThread = new Thread(
                new Producer(clerk));
        Thread consumerThread = new Thread(
                new Consumer(clerk));
 
        producerThread.start();
        consumerThread.start();
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thread class string
相关文章推荐