- //需求:生产烤鸭,生产者生产一份,消费者消费一份,
- //且生产者和消费者是多个。
- class Resourse
- {
- String name;
- int count=1;
- boolean flag = false;
- synchronized void producer()
- {
-
- while(this.flag)
- try{this.wait();}catch(InterruptedException e){}
- System.out.println(Thread.currentThread().getName()+"生产烤鸭"+".........."+this.count);
- this.flag = true;
- this.notifyAll();
-
-
- }
- synchronized void customer()
- {
-
- while(!this.flag)
- try{this.wait();}catch(InterruptedException e){}
- System.out.println(Thread.currentThread().getName()+","+"xiaofei"+"..............................."+this.count);
- this.flag = false;
- this.count++;
- this.notifyAll();
-
-
- }
- }
- class ShengChan implements Runnable
- {
- Resourse r;
- ShengChan(Resourse r)
- {
- this.r = r;
- }
- public void run()
- {
- r.producer();
- }
- }
- class XiaoFei implements Runnable
- {
- Resourse r;
- XiaoFei(Resourse r)
- {
- this.r = r;
- }
- public void run()
- {
- r.customer();
- }
- }
- class Test
- {
- public static void main(String[] args)
- {
- Resourse r = new Resourse();
- ShengChan a = new ShengChan(r);
- XiaoFei b = new XiaoFei(r);
- Thread t1 = new Thread(a);
- Thread t2 = new Thread(a);
- Thread t3 = new Thread(b);
- Thread t4 = new Thread(b);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码
为什么我这个多线程的问题,用notifyAll();了还是死锁啊,试了N次都是每个线程运行了一下。。求大神解答,谢谢 |