public void go() {
while (true) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e){}
if(runFlag)
t.setText(Integer.toString(count++));
}
}
class OnOffL implements ActionListener {
public void actionPerformed(ActionEvent e) {
runFlag = !runFlag;
}
}
为什么这会是一个死循环呢?
但我按下onoffl时,runflag就变成了假,go就自然跳出来来了呢。
但实际上t这个textfiled里的数字会一直跳动,永远不会出来?
有高手解释一下为什么吗?
是think in java中的14 章线程中的第一个例子
while (true) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e){}
if(runFlag)
t.setText(Integer.toString(count++));
}
}
class OnOffL implements ActionListener {
public void actionPerformed(ActionEvent e) {
runFlag = !runFlag;
}
}
为什么这会是一个死循环呢?
但我按下onoffl时,runflag就变成了假,go就自然跳出来来了呢。
但实际上t这个textfiled里的数字会一直跳动,永远不会出来?
有高手解释一下为什么吗?
是think in java中的14 章线程中的第一个例子
import java.awt.event.*;
import java.applet.*;public class Counter1 extends Applet {
private int count = 0;
private Button
onOff = new Button("Toggle"),
start = new Button("Start");
private TextField t = new TextField(10);
private boolean runFlag = true;
public void init() {
add(t);
start.addActionListener(new StartL());
add(start);
onOff.addActionListener(new OnOffL());
add(onOff);
}
public void go() {
while (true) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e){}
if(runFlag)
t.setText(Integer.toString(count++));
}
}
class StartL implements ActionListener {
public void actionPerformed(ActionEvent e) {
go();
}
}
class OnOffL implements ActionListener {
public void actionPerformed(ActionEvent e) {
runFlag = !runFlag;
}
}
public static void main(String[] args) {
Counter1 applet = new Counter1();
Frame aFrame = new Frame("Counter1");
aFrame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
aFrame.add(applet, BorderLayout.CENTER);
aFrame.setSize(300,200);
applet.init();
applet.start();
aFrame.setVisible(true);
}
} ///:~
这是完整的代码
也没看tij中的代码.所以只是分析一下:
在go()中,while(true){}就是死循环.
触发onoffl事件后runFlag会为false;之后t的数字应该不会变化,直到再次触发onoffl事件;
触发onoffl事件会给currentThread一个中断信号,如果不在while(true){}语句中捕捉InterruptedException ,则线程结束.
但是既然处理了这个InterruptedException,所以线程仍然"活着",继续循环所以是一个死循环,而且线程不会因为onoffl事件而退出.t会有变化.
............
在没有被通知、中断或超时的情况下,线程还可以唤醒一个所谓的虚假唤醒 (spurious wakeup)。虽然这种情况在实践中很少发生,但是应用程序必须通过以下方式防止其发生,即对应该导致该线程被提醒的条件进行测试,如果不满足该条件,则继续等待。换句话说,等待应总是发生在循环中,如下面的示例:
synchronized (obj) {
while (<condition does not hold>)
obj.wait(timeout);
... // Perform action appropriate to condition
}
(有关这一主题的更多信息,请参阅 Doug Lea 撰写的 Concurrent Programming in Java (Second Edition) (Addison-Wesley, 2000) 中的第 3.2.3 节或 Joshua Bloch 撰写的 Effective Java Programming Language Guide (Addison-Wesley, 2001) 中的第 50 项。
楼主的代码应该是个实例,行为可能是:但按下onoffl时,runflag就变成了假,textfiled里的数字会停止跳动但是go方法不会跳出来。线程仍在运行。
除非在cmd中用ctrl+c退出。
我的理解是按下onoff后,runflag变false
然后 count就不再++了。