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

有关Java线程wait后唤醒的问题
一般来说,wait后要通过notify来唤醒,但是最近看书写的一个小程序,没有notify也唤醒了,不知道什么原因,还望论坛里的大神赐教。


源代码如下:

package edu.cczu.mythread1;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class Commnicate extends JFrame{

Thread t1;
Thread t2;
private int count=0;
final JProgressBar progressBar = new JProgressBar();
public static void main(String[] args) {
init(new Commnicate(),150,100);

}
public Commnicate() {
super();
progressBar.setStringPainted(true);
getContentPane().add(progressBar, BorderLayout.NORTH);
deValue();
addValue();
t1.start();
t2.start();
}
public void addValue(){
t1=new Thread(new Runnable(){
public void run(){
try{
Thread.currentThread().sleep(10000);
System.out.println("线程退出");
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public void deValue(){
t2=new Thread(new Runnable(){
public void run(){
while (true) {
if(count==0){
synchronized (t1) {
try {
System.out.println("t2等待");
t1.wait(); //这里应该等待,为什么t1结束后就被唤醒了?
System.out.println("t2等待结束");
count = 10;
} catch (Exception e) {
e.printStackTrace();
}
}
}
progressBar.setValue(--count);
System.out.println("进度条的当前值为:" + count);
}
}
});
}
public static void init(JFrame frame,int width,int height){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
}

t1.wait(); //这里应该等待,为什么t1结束后就被唤醒了?
当然只是执行了一次,第二次就停在那儿了。

------解决方案--------------------
好像是thread的终结让Thread这个对象本身的wait()方法失效了。如果你把Sleep(10000)移到t1.start()后面,然后加上t1.wait(),自然要用synchronized包住这三句话,你会发现main线程是不会进入BLOCKED状态的。具体为啥还是要请高手来解答了。不过就楼主这个应用,不应该用t1直接当做锁,新建一个Object,然后用它来当锁才是正解
------解决方案--------------------
楼主可以参考以下:
http://bbs.csdn.net/topics/390352356