我有以下代码:
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
会使这段代码起作用?
最佳答案
即使使用Thread.sleep()
,它也可能不起作用。这是因为您没有正确同步对共享 ThrCount
变量的访问。
如果您将该变量设为 volatile
,您应该不会再看到任何问题。但是,由于 ++
操作不是原子操作,因此它可能不会恰好循环 10 次。
理想情况下,您应该使用 AtomicInteger 并使用其 incrementAndGet()
方法。
另请注意:
- Java 命名约定:变量和方法名称应以小写字母开头(
thrCount
、thrCountIncr()
sleep
是一个静态方法,因此您只需调用Thread.sleep(...);
即可在当前线程中 hibernate 。
关于java - 如果没有 Thread.sleep(...) 调用,线程代码将无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13364863/