Working with Threads-Java in a Nutshell, 6th

來源:互聯網
上載者:User

標籤:

In order to work effectively with multithreaded code, it’s important to have the basic

facts about monitors and locks at your command. This checklist contains the main

facts that you should know:

  • Synchronization is about protecting object state and memory, not code.

    同步是關於保護對象的狀態和記憶體,不是代碼.

  • Synchronization is a cooperative mechanism between threads. One bug can break the cooperative model and have far-reaching consequences.

    同步是線程間相互合作的一種機制,一個bug就可能打破合作模型,導致嚴重的後果.

  • Acquiring a monitor only prevents other threads from acquiring the monitor—it does not protect the object.

    一個線程獲得一個monitor,只能防止其它線程獲得這個monitor---monitor不能保護對象.

  • Unsynchronized methods can see (and modify) inconsistent state, even while the object’s monitor is locked.

    沒有同步的方法能看到(且修改)對象不一致的狀態,即使對象的monitor已被上鎖.

  •  Locking an Object[] doesn’t lock the individual objects.

    對一個Object[]數組上鎖,並不能鎖住數組內的每一個對象.

  • Primitives are not mutable, so they can’t (and don’t need to) be locked.

    原生類型是不可變的,所以他們不能(而且沒必要)去上鎖.

  • synchronized can’t appear on a method declaration in an interface.

    同步不能出現在介面的方法上.

  • Inner classes are just syntactic sugar, so locks on inner classes have no effect on the enclosing class (and vice versa).

    內部類僅僅是文法糖而已,所以對內部類上鎖不會影響包含它的類(反之亦然).

  • Java’s locks are reentrant. This means that if a thread holding a monitor encounters a synchronized block for the same monitor, it can enter the block.

  • Java
  • 的鎖是重入鎖.這就意味著如果一個線程碰到一個同步塊而擁有了一個
  • monitor,這個線程還是可以進入這個同步塊.

Working with Threads-Java in a Nutshell, 6th

相關文章

聯繫我們

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