volatile不能保证原子性

mac2024-04-20  44

public class T { volatile int count = 0; void m() { for(int i=0; i<10000; i++) count++; } public static void main(String[] args) { T t = new T(); List<Thread> threads = new ArrayList<Thread>(); for(int i=0; i<10; i++) { threads.add(new Thread(t::m, "thread-"+i)); } threads.forEach((o)->o.start()); threads.forEach((o)->{ try { o.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println(t.count); } }

volative虽然可以保证可见性,但是不能保证原子性

所以这里的程序,我们期望最终的结果是10 × 10000,但是事实事与愿违。

因为自增操作不是原子性的。

自增包括两步, 

第一是获取该值

第二是自增

那么这中间就可能被其他线程打断。

最新回复(0)