Java之voliate, synchronized, AtomicInteger使用

來源:互聯網
上載者:User

標籤:

1: voliate 

 用在多線程,同步變數。 線程為了提高效率,將成員變數(如A)某拷貝了一份(如B),線程中對A的訪問其實訪問的是B。只在某些動作時才進行A和B的同步。因此存在A和B不一致的情況。volatile就是用來避免這種情況的。volatile告訴jvm, 它所修飾的變數不保留拷貝,直接存取主記憶體中的(也就是上面說的A) ,但是不能用其來進行多線程同步控制

public class Counter {    public volatile  static int count = 0;    public static void inc() {        //這裡延遲5毫秒,使得結果明顯        try {            Thread.sleep(5);        } catch (InterruptedException e) {        }        //synchronized(Counter.class) {        count ++;        //}    }     public static void main(String[] args) throws InterruptedException {     final CountDownLatch latch = new CountDownLatch(1000);        //同時啟動1000個線程,去進行i++計算,看看實際結果        for (int i = 0; i < 1000; i++) {            new Thread(new Runnable() {                @Override                public void run() {                    Counter.inc();                    latch.countDown();                }            }).start();        }        latch.await();        //這裡每次啟動並執行值都有可能不同,可能為1000        System.out.println("運行結果:Counter.count=" + Counter.count);    }}

可以看到,運行結果:Counter.count=929(數字隨機),但如果將注釋掉的同步塊synchronized開啟,console輸出則為1000

 2.synchronized

它用來修飾一個方法或者一個代碼塊的時候,能夠保證在同一時刻最多隻有一個線程執行該段代碼。

     一、當兩個並發線程訪問同一個對象object中的這個synchronized(this)同步代碼塊時,一個時間內只能有一個線程得到執行。另一個線程必須等待當前線程執行完這個代碼塊以後才能執行該代碼塊。

     二、然而,當一個線程訪問object的一個synchronized(this)同步代碼塊時,另一個線程仍然可以訪問該object中的非synchronized(this)同步代碼塊。

     三、尤其關鍵的是,當一個線程訪問object的一個synchronized(this)同步代碼塊時,其他線程對object中所有其它synchronized(this)同步代碼塊的訪問將被阻塞。

     四、第三個例子同樣適用其它同步代碼塊。也就是說,當一個線程訪問object的一個synchronized(this)同步代碼塊時,它就獲得了這個object的對象鎖。結果,其它線程對該object對象所有同步代碼部分的訪問都被暫時阻塞。

     五、以上規則對其它對象鎖同樣適用.

3:AtomicInteger

使用AtomicInteger,即使不用同步塊synchronized,最後的結果也是1000,可用看出AtomicInteger的作用,用原子方式更新的int值。主要用於在高並發環境下的高效程式處理。使用非阻塞演算法來實現並發控制。

public class Counter {   public  static AtomicInteger count = new AtomicInteger(0);    public static void inc() {         //這裡延遲1毫秒,使得結果明顯        try {            Thread.sleep(1);        } catch (InterruptedException e) {        }        count.getAndIncrement();    }     public static void main(String[] args) throws InterruptedException {        final CountDownLatch latch = new CountDownLatch(1000);        //同時啟動1000個線程,去進行i++計算,看看實際結果        for (int i = 0; i < 1000; i++) {            new Thread(new Runnable() {                @Override                public void run() {                    Counter.inc();                    latch.countDown();                }            }).start();        }        latch.await();        //這裡每次啟動並執行值都有可能不同,可能為1000        System.out.println("運行結果:Counter.count=" + Counter.count);    }}


Java之voliate, synchronized, AtomicInteger使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.