请高手帮我看一个有关多线程同步的问题
大家好,本贴转自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();
} catch (InterruptedException e) {
System.out.println( "wait error! ");
}
}
counter -= 1;
System.out.println( "min counter: " + counter);
notifyAll();
}
}
class NewThread implements Runnable {
public Thread t;
private boolean add;
Q q;
NewThread(String name, boolean add, Q q) {
t = new Thread(this, name);
this.add = add;
this.q = q;
System.out.println(t.getName() + " is starting... ");
t.start();
}
public void run() {
try {
while (true) {
t.sleep(1000);
if (add) {// Producer
System.out.println(t.getName());
q.addCounter(t.getName());
} else {
System.out.println(t.getName());// Consumer
q.minCounter(t.getName());
}
}
} catch (Exception e) {
System.out.println( "error occurs ");
} finally {
System.out.println( "thread " + t.getName()
+ "exiting......................... ");
}
}
}
[解决办法]
经典!!!
[解决办法]
Thus, it is best to treat thread priorities only as hints to the scheduler. You should never structure your programs so that their correct functioning depends on priority levels.
(因此,最好仅将线程的优先级看作一个参考因素,不要吧程序构建为其功能的正确性依赖于优先级)
摘自core java 7th (二)16页
有空自己去看下吧,上面关于楼主问的 while ,notify函数和notifyAll() 将的很清楚,太多了,懒的打了
