多个生产者与消费者

今天早上敲代码时发现了好多问题,Xiao(RongQi r) {this.r = r;},这段代码我一直搞不懂,既然上面已经private RongQi r,为什么还要多此一举,其实创建Xiao对象时把RongQi 对象地址传给this.r也就是private RongQi r的r这样你调用put,get方法时就能找到RongQi对象。
多生产多消费要注意一个问题,等待唤醒机制是在判断里面的,当一个生产者唤醒另外一个生产者时,没有进行判断就进行生产了,那么就会造成安全问题,所以将if语句换成while语句,唤醒语句要改成notifyAll,因为会出现生产与消费都在线程池里的现象。

class RongQi {
    private Object[] o = new Object[1];
    private Object obj = new Object();
    int num = 0;

    public void put(Object obj) {
        synchronized (obj) {
            while (o[0] != null) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {

                }
                o[0] = obj+"--"+num;
                num++;
                System.out.println(Thread.currentThread().getName() + "生产者生产的---" +o[0]);
                obj.notifyAll();
            }

        }
    }

    public void get() {
        synchronized (obj) {
            while (o[0] == null) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {

                }
                System.out.println(Thread.currentThread().getName() + "消费者消费的---" +o[0]);
                o[0]=null;
                obj.notifyAll();

            }
        }
    }
}

class Chan implements Runnable {
    private RongQi r;

    Chan(RongQi r) {
        this.r = r;
    }

    public void run() {
        while (true) {
            r.put("牛奶");
        }
    }
}

class Xiao implements Runnable {
    private RongQi r;

    Xiao(RongQi r) {
        this.r = r;
    }

    public void run() {
        while (true) {
            r.get();
        }
    }
}

class Demo1 {
    public static void main(String[] args) {
        RongQi r = new RongQi();
        Chan c = new Chan(r);
        Xiao x = new Xiao(r);
        Chan c1 = new Chan(r);
        Xiao x1 = new Xiao(r);
        Thread t = new Thread(c);
        Thread t2 = new Thread(c1);
        Thread t3 = new Thread(x);
        Thread t4 = new Thread(x1);
        t.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

你可能感兴趣的:(多个生产者与消费者)