- class Resource
- {
- private String name;
- private int count=1;
- private boolean flag=false;
- //注释一
- public synchronized void set(String name)//①t1拥有执行权 t2等待->②执行到notify()唤醒t2,t1判断标识后执行wait(),等待->③t2开始执行
- {
- if(flag)
- try
- {
- this.wait();
- }
- catch (InterruptedException e)
- {
- }
- this.name=name+count;
- count++;
- System.out.println(Thread.currentThread().getName()+"...生产者"+this.name);
- flag=true;
- this.notify();
- }
- public synchronized void out()//t3等待 t4等待
- {
- if(!flag)
- try
- {
- this.wati();
- }
- catch (InterruptedException e)
- {
- }
- System.out.println(Thread.currentThread().getName+"...消费者"+this.name);
- flag=false;
- this.notify();
- }
- }
- 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 ThreadDemo
- {
- public static void main(String[] args)
- {
- Resource r=new Resource();
- Producer pro=new Producer(r);
- Consumer con=new Consumer(r);
- Thread t1=new Thread(pro);
- Thread t2=new Thread(pro);
- Thread t3=new Thread(con);
- Thread t4=new Thread(con);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 毕老师讲解多生产多消费时的代码事例
如上述代码注释一:
①t1拥有执行权,t2等待,t1执行同步代码,输出:Thread-0......生产者....面包2499,更改flag=true,执行notify()唤醒t2;
②此时t1仍然持有锁对象以及执行权,t1继续执行同步代码,首先进行if判断,flag为true,执行wait(),t1释放锁对象,处于等待状态;
③t2持有锁,开始执行同步代码。
疑点:此时flag仍然为true,为什么t2不需要进行if判断,可以继续执行下面的代码,
输出: Thread-1......生产者.....2500
|
|