Cher ZY
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 模組24 多執行緒同步(Synchronization、synchronized、Thread-safe) 寫得縮略一點,以例子說明之。 > 某公司的某產品庫存量為 100 個,某一天 A 和 B 同時進貨,在 A 進貨 20 個的同時,B 也進貨品 30 個。 ## 2 個以上的執行緒存取相同資源 > A 和 B 同時更新庫存量,並且不知道彼此正在更新。 <table class="x_nosync"> <tr> <td colspan="2">原貨量:x = 100</td> </tr> <tr> <td>A 讀取:x = 100</td> <td></td> </tr> <tr> <td></td> <td>B 讀取:x = 100</td> </tr> <tr> <td>A 更新:x = 100 + 20</td> <td></td> </tr> <tr> <td></td> <td>B 更新:x = 100 + 30</td> </tr> <tr> <td>A 存檔:x = 120</td> <td></td> </tr> <tr> <td></td> <td>B 存檔:x = 130</td> </tr> <tr> <td colspan="2">最終貨量(錯誤): x = 130<br>(因為 B 最後更新)</td> </tr> </table> <style> .x_nosync { width: 600px; text-align: center; } .x_nosync tr td { width: 300px; } </style> 例子當中因為 B 最後才更新,所以最終貨量會以最新的資料為主。 但即使是 A 先完成存檔,貨量是 120 的狀況,也仍然錯誤。 因為實際的最終貨量應該是 150 個。 ## Critical Section(危險區域)的概念 會造成這樣的狀況有幾個條件: 1. A 和 B 在同時段存取並異動了同個資源。 2. A 和 B 不知道彼此在同時段存取並異動資源。 **兩個人都在存取資源的區域就稱為 Critical Section(危險區域)**。 在程式的 Critical Section 裡,不同執行緒可能同時存取同一份資源,因而產生衝突或重複修改的問題。 ## 解決方式:Synchronization 可以破解條件的辦法: 1. 同時間內,**A 和 B 只能有一個人存取資源;其中一個人若正在存取資源,就不允許另外一個人存取資源**。 2. 有一個額外的監控角色,能精準控制 2 個人存取資源的行為。 Synchronization(同步化)就是為了實現這樣的解決辦法,但是以「**限制空間進出**」的方式達到「同時段內限制一個執行緒存取」的概念,其中很具體的設計了 **Monitor**(區域監控)和 **Lock**(鎖,又稱 Flag)的機制。 ## Synchronization(同步化)與 synchronized 關鍵字 先大致說明一下我理解的 Monitor 和 Lock。 ### Monitor 與 Lock 找到 Critical Section 後,選擇用 `synchronized` 關鍵字包起來的區域(包起來的範圍粗略可分為兩種,細分可以算是三種),我們必須監控(Monitor)著,取得 Lock 的執行緒才能進入。 ### 實作步驟 #### 一、找出 Critical Section 的範圍,以便進行 Monitor: 1. 大致範圍:存取相同資源的方法 {} 內。 2. 精確範圍:存取、異動相同資源的程式碼起訖前後。 範圍越大就越耗能。 #### 二、加入 synchronized 關鍵字,進行 Monitor: 1. **在方法宣告中加入**:Critical Section 出現在哪裡,就監控那一整個方法。<div style="margin-bottom:16px;" title="保持間距用"></div> ```java // 省略宣告、指定 x,及呼叫並傳入 x 的動作 // 省略建立 Thread 的動作 void synchronized updateCount(int x, count) {} ``` 2. **另外標示出 synchronized 程式區塊**:縮小監控範圍,只監控 Critical Section 有存取、異動資源的那幾行程式碼。 1. 標示監控哪個物件的鎖(Lock)<div style="margin-bottom:16px;" title="保持間距用"></div> ```java // 省略宣告、指定 x,及呼叫並傳入 x 的動作 // 省略建立 Thread 的動作 void updateCount(count) { synchronized (x) { x += count; } } ``` 2. 標示監控哪個類別資料(Name.class):使用在有 static 資料的狀況<div style="margin-bottom:16px;" title="保持間距用"></div> ```java public class TestSync { static int x = 100; void updateCount(count) { synchronized (this) { // this 是在相同類別下,標示監控「這個」類別 // 可以精確地寫成 TestSync.class,監控區域在不同類別更應該這麼寫 x += count; } } } ``` ### 同步與系統效能、穩定度 同步化的使用,與其消耗的系統效能及系統的穩定度都成正比: 1. 因為本身就很耗時,所以**使用越多,或範圍越大,系統資源越消耗**。 2. 如果是常常要執行的方法或程式區段,**除非必要,否則應該要減少使用**。 3. 雖然如此,同步化卻會相對**提高穩定度、強健度**。 結論:**需要妥善的運用同步化**。 ## 補充 先前在[介紹集合物件時](/tGwjsD53TKOI31SSfKf1AQ#集合相關的API架構圖)有提到 Vector、Hashtable,其實兩者就是 **Thread-safe(執行緒安全**,指已有做同步處理)的 ArrayList 和 HashMap。 Vector、Hashtable 和 ArrayList、HashMap 基本使用上是一模一樣,但額外帶來了同步化的優點和負擔。 同步處理機制集合的相關使用,可參考 ==Collections 類別==(注意是 Collections **類別**,存放有集合相關的操作方法;**並不是**指 Collection 介面) 的 API 文件: https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html 有一堆 synchronized 開頭的方法可以使用。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully