高效並發-安全執行緒與鎖最佳化__JVM學習筆記

來源:互聯網
上載者:User
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:鎖最佳化 自旋鎖與自適應自旋 鎖消除 鎖粗化 輕量級鎖 偏向鎖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.