日期:2014-05-20  浏览次数:20660 次

请高手帮我看一个有关多线程同步的问题
大家好,本贴转自www.java-cn.com上面的,由于问题有点棘手,所以上这里请大家帮忙解答一下!这是我第一次来这里提问,希望大家帮忙,我一定在线(上班)的时候关注此问题,并及时给分。
原贴是:
http://www.java-cn.com/bbs-jsp/show.jsp?id=28967&forum=advanced

现在我有两点问题:
1.当有两个以上的线程同步运行的时候,为什么一定要把   if   改成   while  
2.最好是将notify函数改用notifyAll()   代替(我试了一下,好像都可以用的啊)。  


代码如下:  
package   chapter3;  

/**  
*   @author   cherry   两个线程用作Producer,一个线程用作Consumer  
*   This   version   is   2.0   ,   proposed   by   小狗子  
*   Date   :   2007.4.4  
*/  
public   class   Chapter3   {  
public   static   void   main(String[]   args)   {  
NewThread   a,   b,   c,   d;  
Q   q   =   new   Q();  
a   =   new   NewThread( "1st   producer   ",   true,   q);//   Producer   1  
b   =   new   NewThread( "2nd   producer   ",   true,   q);//   Producer   2  
c   =   new   NewThread( "3rd   producer   ",   true,   q);//   Producer   3  
d   =   new   NewThread( "1st   consumer   ",   false,   q);//   Consumer  
Thread   t   =   Thread.currentThread();  
t.setName( "Main   thread ");  
System.out.println(t.getName()   +   "   is   starting... ");  
try   {  
a.t.join();  
b.t.join();  
c.t.join();  
d.t.join();  
System.out.println( "main   thread   is   exiting.......... ");  
}   catch   (InterruptedException   e)   {  
System.out.println( "error   occurs "   +   e.getMessage());  
}   finally   {  

}  
}  
}  

/**  
*   @author   cherry   Class   Q   is   used   to   implement   comsumer   and   producer  
*/  
class   Q   {  
private   static   int   counter   =   0;  

synchronized   void   addCounter(String   threadName)   {  
//   must   use   while   condition   here,instead   of   if   condition  
while   (counter   > =   10)   {//   生成过剩就等待  
try   {  
System.out.println(threadName   +   "   add   is   waiting ");  
wait();  

}   catch   (InterruptedException   e)   {  
System.out.println( "wait   error! ");  
}  
}  
counter   +=   1;  
notifyAll();//   use   notify()   seems   also   right   here  
System.out.println( "add   counter:   "   +   counter);  
}  

synchronized   void   minCounter(String   threadName)   {  
//   must   use   while   condition   here,instead   of   if   condition  
while   (counter   ==   0)   {//   消费过渡就等待  
try   {  
System.out.println(threadName   +   "   minus   is   waiting ");  
wait();