volatile不会提供加锁机制,只会保证修改对其他线程的可见性,当只有一个线程修改变量值,多个线程读取变量值时可以使用volatile,当多个线程修改变量值时,不能保证变量的安全,会发生丢失更新现象。
class="java">import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Test { volatile static int m = 0; public static void main(String[] args) throws InterruptedException { ExecutorService exec = Executors.newCachedThreadPool(); for (int j = 0; j < 10; j++) { exec.execute(new Runnable() { int count = 1000; @Override public void run() { while (count-- > 0) m++; } }); } exec.shutdown(); while (Thread.activeCount() > 1) { Thread.yield(); } System.out.println(m); } }
?