- class Resource
- {
- private String name;
- private int count = 1;
- private boolean flag = false;
- public synchronized void set(String name)
- {
- if(flag) {
- try{this.wait();}catch(InterruptedException e){}
- } else {//老师讲的是用while来判断防止生产一个消费多个的问题,我这样用if else 来判断是不是也可以也不会出现安全问题
- this.name = name + count;
- count++;
- System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
- flag = true;
- notifyAll();
- }
- }
- public synchronized void out()// t3
- {
- if(!flag) {
- try{this.wait();}catch(InterruptedException e){}
- }else {
- System.out.println(Thread.currentThread().getName()+"...消费者........"+this.name);
- flag = false;
- notifyAll();
- }
- }
- }
- class Producer implements Runnable
- {
- private Resource r;
- Producer(Resource r)
- {
- this.r = r;
- }
- public void run()
- {
- while(true)
- {
- r.set("烤鸭");
- }
- }
- }
- class Consumer implements Runnable
- {
- private Resource r;
- Consumer(Resource r)
- {
- this.r = r;
- }
- public void run()
- {
- while(true)
- {
- r.out();
- }
- }
- }
- class ProducerConsumerDemo
- {
- public static void main(String[] args)
- {
- Resource r = new Resource();
- Producer pro = new Producer(r);
- Consumer con = new Consumer(r);
- Thread t0 = new Thread(pro);
- Thread t1 = new Thread(pro);
- Thread t2 = new Thread(con);
- Thread t3 = new Thread(con);
- t0.start();
- t1.start();
- t2.start();
- t3.start();
- }
- }
复制代码 我这样用if else是不是也可以避免出现生产一个消费多个的问题,自己写的时候这样写了感觉应该也没问题,不大肯定,帮忙看看,谢谢 |