直接上代碼:java
一個靜態變量B,一個靜態方法addB,調用線程池循環增長B,若是不加synchronized關鍵字給addB方法,則會出現不等於1000的問題:app
即便此時爲B添加volatile,仍是不等於正確答案1000.線程
添加synchronized後,纔是正確答案1000;code
package org.braven.servlet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class App { static int B = 0; //static volatile int B = 0; static synchronized void addB() { try { Thread.sleep(1); } catch (Exception e) { // TODO: handle exception } B++; } public static void main(String[] args) throws InterruptedException { /*for (int i = 0; i < 1000; i++) { new Thread(new Runnable() { public void run() { addB(); } }).start(); }*/ ExecutorService pool = Executors.newFixedThreadPool(20); for (int i = 0; i < 1000; i++) { pool.submit(new Runnable() { public void run() { addB(); } }); } Thread.sleep(2000); System.out.println("B最終等於:" + B); App app1 = new App(); App app2 = new App(); System.out.println(app1.B); System.out.println(app2.B); App.addB(); System.out.println(app1.B); System.out.println(app2.B); } }