我有以下代码:
public class ThreadTest implements Runnable {
public int ThrCount = 0;
public void ThrCountIncr() {
while (true) {
ThrCount++;
System.out.println(ThrCount);
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run() {
while (true) {
if (ThrCount > 10) {
System.out.println(ThrCount + "\n Thread finished");
System.exit(1);
}
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
但是,当我从 中删除此行时run
,它会停止工作:
Thread.currentThread().sleep(100);
首先,我启动线程,然后使用ThrCountIncr
.
ThreadTest Thrtest = new ThreadTest();
Thread thr = new Thread(Thrtest);
thr.start();
Thrtest.ThrCountIncr();
线程检查ThrCount
变量值,如果大于 10,则停止程序。没有sleep(100)
,线程不会停止程序,我认为它不会检查变量值。为什么调用sleep
使此代码起作用?