码迷,mamicode.com
首页 > 编程语言 > 详细

java 多线程生产者消费者

时间:2020-03-31 23:09:15      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:flag   dex   getname   span   生产者   main   cer   start   判断   

 

class Res {
    private String name;
    private int count = 1;
    private boolean flag;

    public synchronized void set(String name) {
        while (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name + "--" + count++;
        System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
        flag = true;
        this.notifyAll();
    }

    public synchronized void print() {
        while (flag) {
            System.out.println(Thread.currentThread().getName() + "......消费者......" + this.name);
            flag = false;
            this.notifyAll();
        }
    }
}

class Producer implements Runnable {
    private Res r;

    public Producer(Res r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
            r.set("商品");
        }
    }
}

class Consumer implements Runnable {
    private Res r;

    public Consumer(Res r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
            r.print();
        }
    }
}

public class ProducerConsumerDemo {
    public static void main(String[] args) {
        Res r = new Res();
        new Thread(new Producer(r)).start();
        new Thread(new Producer(r)).start();
        new Thread(new Consumer(r)).start();
        new Thread(new Consumer(r)).start();

    }
}
出现多个生产者消费者要用while重新判断一次标记,并使用notifyAll()唤醒所有,notify可能出现只唤醒本方线程的情况,导致所有线程都等待。

java 多线程生产者消费者

标签:flag   dex   getname   span   生产者   main   cer   start   判断   

原文地址:https://www.cnblogs.com/hongxiao2020/p/12608866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!