java笔记→java线程的通讯问题(生产者与消费者)

来源:互联网 发布:内外网络切换器软件 编辑:程序博客网 时间:2024/06/06 15:55

java线程的通讯问题(生产者与消费者)

使用wait()与notify()方法来控制。
生产者使用wait等待并使用notify来通知消费者来消费,
消费者消费完使用wait等待并使用notify来通知生产者进行生产。

**/** * 产品类 */public class Product {    int n = 0;    int i=0;    boolean valueSet = false;    public synchronized void put() {        if (valueSet == true) {            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        i++;        System.out.println("生产产品:" + i);        valueSet=true;        notify();    }    public synchronized void get() {        if (valueSet == false) {            try {                wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        n++;        System.out.println("消费产品:" + n);        valueSet=false;        notify();    }}/** * 生产者类 */public class Producer implements Runnable {    Product consumer;    public Producer(Product consumer) {        this.consumer = consumer;        new Thread(this).start();    }    public void run() {        while(true){            consumer.put();            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}/** * 消费者类 */public class Consumer implements Runnable {    Product consumer;    public Consumer(Product consumer) {        this.consumer = consumer;        new Thread(this).start();    }    public void run() {        while(true){            consumer.get();            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}/** * 测试类 */public class Test {    public static void main(String[] args){        Product consumer=new Product();        Producer producer=new Producer(consumer);        Consumer product=new Consumer(consumer);    }}**
0 1