1:安全執行緒
1.1:Java語言中的安全執行緒
不可變:被final修飾。
絕對安全執行緒 **相對安全執行緒:**Java語言中,大部分的安全執行緒類都屬於這種類型,例如Vector、HashTable、Collections的 synchronizedCollection()方法封裝的集合
線程相容:對象本身不是現場安全的,但可以通過在調用端通過正確的使用同步手段來保證在並發環境下安全的使用。
線程對立:無論調用端是否採取了同步措施,都無法在多線程環境中並發使用的代碼。
1.2:安全執行緒的實現方法
互斥同步: 互斥是因,同步是果;互斥是方法,同步是目的。 synchronize和 ReentrantLock(可實現等待可中斷,公平鎖,鎖綁定多個條件)。
非阻塞同步: CAS同步方案:
/** 1. Atomic變數自增運算測試 2. */public class AtomicTest { public static AtomicInteger race = new AtomicInteger(0); public static void increase() { race.incrementAndGet(); } private static final int THREADS_COUNT = 20; public static void main(String[] args) throws Exception { Thread[] threads = new Thread[THREADS_COUNT]; for (int i = 0; i < THREADS_COUNT; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10000; i++) { increase(); } } }); threads[i].start(); } while (Thread.activeCount() > 1) Thread.yield(); System.out.println(race); }}
/** * Atomically increment by one the current value. * @return the updated value */ public final int incrementAndGet() { for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return next; } }
3. 無同步方案
可重新進入代碼:這種代碼也叫作純程式碼,可以在代碼執行的任意時候去中斷,轉而去執行另外一段代碼(包括遞迴調用他本身),而在控制權返回後,原來的程式不會出現任何錯誤。
執行緒區域儲存:如果一段代碼所需要的資料必須與其他 代碼共用,那就看看這些共用資料的代碼是否能保證在同一個線程中執行。 1.3:鎖最佳化 自旋鎖與自適應自旋 鎖消除 鎖粗化 輕量級鎖 偏向鎖