毕老师视频中的一个例子,我稍微改了下,结果不太对,请各位大神帮忙看看问题出在哪
- package java01;
- import java.util.concurrent.locks.*;
- class Resource
- {
- private String name;
- private boolean flag=false;
- private int count=0;
- Lock lock = new ReentrantLock();
- Condition pro = lock.newCondition();
- Condition con = lock.newCondition();
-
- public void set(String name)
- {
- lock.lock();
- if(flag)
- try{pro.await();}catch(Exception e){}
- this.name=name+":"+count++;
- System.out.println(Thread.currentThread().getName()+" 生产者 "+name);
- flag=true;
- con.signal();
- lock.unlock();
- }
- public void out()
- {
- lock.lock();
- if(!flag)
- try{con.await();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+" 消费者 "+name);
- flag=false;
- pro.signal();
- lock.unlock();
- }
- }
- 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();
- }
- }
- }
- public class day1212 {
- public static void main(String[] args) {
- Resource r = new Resource();
- new Thread(new Producer(r)).start();
- new Thread(new Producer(r)).start();
- new Thread(new Consumer(r)).start();
- new Thread(new Consumer(r)).start();
- }
- }
复制代码
|
|