hen*_*les 1 java multithreading
我知道有很多主题可用于堆栈溢出但是当我试图从理论上学习volatile关键字时我相信它对我很清楚但是当我尝试运行以下示例时我的理解失败或者我无法将序列可视化.
了解挥发性 - >Making variable as volatile for an instance, makes it non cacheable for threads that means whichever thread is accessing the volatile variable it has to flush the changes into the main memory immediately so that changes should be visible to other thread.
但是在这个例子中,如果你看到输出当threadA将值写为6被计为volatile时它应该被刷新到主内存中,所以当线程B看到这个更改时它应该看到更改但是线程B显示2而不是6或7
我无法想象线程,请你帮我看一下线程执行的发生方式.
public class PerfectExampleToUnderstandVolatile {
public static void main(String[] args) {
ThreadSample sample = new ThreadSample();
Thread thread = new Thread(sample,"threadA");
Thread thread1 = new Thread(sample,"threadB");
Thread thread2 = new Thread(sample,"threadC");
thread.start();
thread1.start();
thread2.start();
}
}
class ThreadSample implements Runnable {
volatile int count;
public ThreadSample() {
}
@Override
public void run() {
while (count < 15) {
System.out.println(Thread.currentThread().getName() + " " + count);
count++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
产量
**threadA 0**
threadA 1
threadA 2
threadA 3
threadA 4
threadA 5
**threadA 6** at this point thread A writes 6
**threadB 0** so here thread B should show 6
threadA 7
**threadC 6** same should be here
threadC 9
threadA 10
threadB 11
threadB 13
threadB 14
threadA 12
threadC 11
Run Code Online (Sandbox Code Playgroud)
输出中没有矛盾:
线程B可以启动,看到count为0,构建一个字符串"threadB 0"并转到'sleep'.然后,当他醒来时,他将它打印到控制台(尽管真正的计数值是那个时刻的6)
线程C可以与6完全相同而不是0.
另外,递增操作count++不是原子的,count ++等于
int temp = count + 1;
count = temp;
Run Code Online (Sandbox Code Playgroud)
如果两个线程同时递增计数,则值可能会递增1而不是2.这就是为什么不应对volatile变量使用递增运算,而是使用AtomicInteger.