/*
*
生产者消费者问题处理*/class Resource
{
String name;
int count = 1;
boolean flag = false; synchronized void  set(String name)
{
while(flag)
try{wait();}catch(InterruptedException i){}
this.name = name +count;
count++;
System.out.println(Thread.currentThread().getName()+".....生产了...." + this.name);
flag =true;
notifyAll(); }
 
synchronized void  out()
{
while(!flag)   //如果最初t2开始执行,获取了同步函数的使用权,
//这个时候,其他的进程t0,t1,t3在妄图执行run方法的时候,发现他们遇到的同步函数
// 已经被锁上,根本无法访问,这个时候,t2判断flag =false ; !flag为真。
//于是t2进入等待状态,
//然后t2就一直等待,等待其他的线程将其唤醒。
//但是t2已经占据了该同步的函数的锁。
//t1,t3,t0根本无法进入同步代码块,又怎么能够唤醒t2呢。
//程序就会在t2的不断等待中...,在其他线程不断的试图进入同步函数中...
//但是t2永远 不会醒,t0,t1,t3永远无法进入。
//这里的理解存在什么错误么??? try{wait();}catch(InterruptedException i){};
System.out.println(Thread.currentThread().getName()+"............消费了..........."+this.name);
flag =false;
notifyAll(); }
}class Producer implements Runnable
{
Resource r;
Producer(Resource r)
{
this.r = r;
} public void run()
{
while(true)
r.set("烤鸭");
}
}class Consumer implements Runnable
{
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 p = new Producer(r);
Consumer c = new Consumer(r); Thread t0 = new Thread(p);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
Thread t3 = new Thread(c); t0.start();
t1.start();
t2.start();
t3.start();
}
}
问题在代码的第二十七行!

解决方案 »

  1.   

    wait方法会释放掉锁,所以,其他线程就有机会得到锁了。
    The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
      

  2.   

    你的理解是错的,首先要想使用wait(),notify/notifyall()方法进行线程之间的同步通信,就要保证所有线程处于同一个同步监视器下,也就说他们要使用同一把锁,当一个线程进入方法体获得锁后,如果他调用了wait()方法,则他会处于该锁的阻塞队列中,并且会释放对该锁的控制权,这样其他线程就可以继续获得该锁了。wait()方法和sleep()方法是不一样的,虽然他们都会阻塞当前线程,但是sleep()阻塞线程的同时,不会释放当前线程所持有的锁,而wait()会释放当前线程所持有的锁。
      

  3.   

    线程这个问题感觉在Java里面好麻烦