我搜索了“java race condition”,看到了很多文章,但没有一篇是我要找的。p>
我试图在不使用锁、同步、Thread.sleep 的情况下解决竞争条件。我的代码在这里:
public class Test {
static public int amount = 0;
static public boolean x = false;
public static void main(String[] args) {
Thread a = new myThread1();
Thread b = new myThread2();
b.start();
a.start();
}
}
class myThread1 extends Thread {
public void run() {
for (int i = 0; i < 1000000; i++) {
if (i % 100000 == 0) {
System.out.println(i);
}
}
while(true){
Test.x = true;
}
}
}
class myThread2 extends Thread {
public void run() {
System.out.println("Thread 2: waiting...");
while (!Test.x) {
}
System.out.println("Thread 2: finish waiting!");
}
}
我希望输出应该是:
Thread 2: waiting...
0
100000
200000
300000
400000
500000
600000
700000
800000
900000
Thread 2: finish waiting!
(Terminated normally)
但实际上是:
Thread 2: waiting...
0
100000
200000
300000
400000
500000
600000
700000
800000
900000
(And the program won't terminate)
在我向 myThread2 添加语句后,发生了变化
while (!Test.x) {
}
到
while (!Test.x) {
System.out.println(".");
}
程序正常终止并且输出是我所期望的(除了那些“。”)
我知道当 2 个线程并发执行时,CPU 可能会在获取机器代码的下一条指令之前任意切换到另一个线程。 我认为如果一个线程读取变量而另一个线程写入变量会很好。而且我真的不明白为什么程序不能正常终止。我也尝试在myThread1 的while 循环中添加Thread sleep 语句,但程序仍然不会终止。
这个问题困扰了我几个星期,希望有人能帮帮我。
最佳答案
尝试将 x 声明为 volatile
:
static public volatile boolean x = false;
关于java - 尝试在不使用 Java 中的任何库的情况下解决竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37310618/