无论有没有volatile关键字,我都会得到相同的输出。
我在代码中犯了错误吗?
public class MutliThreadExample extends Thread{
volatile int value;
public static void main(String[] args) throws InterruptedException {
MutliThreadExample thread1 = new MutliThreadExample();
MutliThreadExample thread2 = new MutliThreadExample();
thread1.start();
thread1.join();
thread2.start();
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
value = value + 1;
System.out.println(value + "-" + Thread.currentThread());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我无法volatile在 Java 中正确使用关键字。