我在使用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();
}
}
}
}
我无法正确地在Java中使用volatile
关键字。
AtomicInteger
,而不仅仅是一个 volatile。 - Louis Wassermanthread1.start(); thread1.join(); thread2.start();
是顺序执行的(即不是并行的) - xerx593volatile
使读写操作具有原子性,但它们的组合不具备原子性。例如,请参见 https://www.scaler.com/topics/volatile-keyword-in-java/。对volatile
变量进行递增操作是 不 安全的,需要使用完整的AtomicInteger
。 - Louis Wassermanvolatile
不是关于原子性的,请不要混淆其他人:https://dev59.com/JmIj5IYBdhLWcg3w8JRZ:~:text=Volatile%20and%20Atomic%20are%20two,on%20variables%20are%20performed%20atomically. - Mikhail2048MutliThreadExample
实例都有自己的value
,因此只有一个线程访问它;对于你的代码来说,volatile 真的不是必需的。 - Mark Rotteveel