關於java synchronized關鍵字的一些理解
阿新 • • 發佈:2019-02-08
看了java程式設計思想的併發這一章,發現對於synchronized關鍵字理解不夠到位,看了其他人的部落格,加深了一些理解:http://www.cnblogs.com/GnagWang/archive/2011/02/27/1966606.html
如程式碼:
發現當getValue()方法 不加synchronized關鍵字時,main方法裡的while迴圈裡面會列印奇數,而加了synchronized關鍵字則不會列印。package edu.other; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class AtomicityTest implements Runnable{ private int i=0; public synchronized int getValue(){ return i; } private synchronized void evenIncrement(){ i++; i++; } public void run() { while(true){ evenIncrement(); } } public static void main(String[] args) { ExecutorService exe = Executors.newCachedThreadPool(); AtomicityTest at = new AtomicityTest(); exe.execute(at); while(true){ int val = at.getValue(); if(val%2!=0) System.out.println(val); } } }
這是因為不同執行緒訪問同一物件時,synchronized方法具有一致性,當被某一執行緒執行某一synchronized方法時,其他執行緒執行所有的synchronized方法時都會被阻塞,而對於非synchronized方法則可以併發執行。
當exe.execute(at)時,執行緒池裡的執行緒死迴圈執行evenIncrement(),而getValue()方法不是synchronized時,則主執行緒可以執行,當然會出現奇數的情況。當getValue()方法是synchronized時,當執行evenIncrement()時,所有其他的synchronized型別的方法都會被阻塞,主執行緒也沒辦法訪問,因此不會列印奇數。