首页 > 代码库 > java高级——生产者消费者问题

java高级——生产者消费者问题

多线程是一个很重要的应用,本节讲述多线程中同步问题

public class ThreadDemo {    public static void main(String[] args) {        Resource r = new Resource();        Producer p1 = new Producer(r);        Consumer c1 = new Consumer(r);        new Thread(p1).start();        new Thread(p1).start();        new Thread(c1).start();        new Thread(c1).start();    }}/*资源类*/class Resource {    private String name;    private boolean flag = false;//资源存在标记    //生产资源    public synchronized void set(String name) {        while (flag) {            try {                this.wait();            } catch (Exception e) {                e.printStackTrace();            }        }        this.name = name;        System.out.println(Thread.currentThread().getName() + "生成者" + name);        flag = true;        this.notifyAll();    }    //消费资源    public synchronized void get() {        while (!flag) {            try {                this.wait();            } catch (Exception e) {                e.printStackTrace();            }        }        System.out.println(Thread.currentThread().getName() + "消费者" + name);        flag = false;        this.notifyAll();    }}/*生产者类*/class Producer implements Runnable {    private Resource r;    public Producer(Resource r) {        this.r = r;    }    public void run() {        while (true) {            r.set("商品");        }    }}/*消费者类*/class Consumer implements Runnable {    private Resource r;    public Consumer(Resource r) {        this.r = r;    }    public void run() {        while (true) {            r.get();        }    }}

上面的代码实现了同步外,还解决了生成一次消费一次的工厂生产问题

java高级——生产者消费者问题