Min*_*ine 1 java multithreading
// The problem in Starter()
// with any line before x = 5 ; for example System.out.println(" Anything");
// the result "x = 4"
// but without the result = "x = 9"
// Why??????
public class Starter extends Thread {
private int x = 2;
public static void main(String[] args)
throws Exception{
new Starter().wakeItSo();
}
Starter() {
// Next line (with or without it)
System.out.println("anything");
x = 5;
start();
}
public void wakeItSo()
throws Exception{
//join();
x = x -1;
System.out.println("x = "+ x);
}
public void run() {
x *=2;
}
}
Run Code Online (Sandbox Code Playgroud)
你有竞争条件.
Starter运行的构造函数,初始化x到5然后启动一个新线程.wakeItSo被调用,它访问当前值x并从中减去一个值.如果新线程中的操作首先运行,您可能会得到结果9,如果wakeItSo首先运行,则得到4.首先发生的事情没有明确定义,并且可以在运行之间进行更改.
似乎添加print语句会减慢主线程的速度,以便x新线程中的更新更有可能首先执行.您应该知道,并不总是保证这种情况,您不应该依赖此行为.
要使程序确定地运行,您需要同步两个线程,以便第一个线程等到第二个线程完成运行(例如通过使用Thread.join).
| 归档时间: |
|
| 查看次数: |
173 次 |
| 最近记录: |