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 New
    • 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 Note Insights Versions and GitHub Sync 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 模組21-22 執行緒與多執行緒設計(Thread、Multithreading、Runnable、Life Cycle of Thread) 執行緒是程式中的執行區段,**這個區段中的指令能夠不被其他區段影響,獨立執行**。 執行緒在我們需要時可以啟動,不需要時可以關閉。 之前上課提到的 Garbage Collector 和 `main()` 方法其實也都是執行緒,但屬於特別的種類。 ## 程序(Process)、執行緒(Thread)與資源分配 以情境和觀念來理解: ![](https://i.imgur.com/10xJWi6.png =250x) > 如果想要開一間 7-11,需要知會 7-11 總公司加盟的意願。 > 7-11 其實上面還有統一集團的總公司,也會得知「想加盟開分店」的要求,再向下依層級分配給你資源。 * **硬體**:統一集團。 * **作業系統**:7-11 總公司。 * **應用程式**:各家 7-11。 ![](https://i.imgur.com/hE7VA0Y.png =500x) > 成功開了一間 7-11 分店,店裡最低只要有一位店員(店長)就可以做各項工作。 > 每間分店都是獨立作業,點貨、上架、結帳、打掃,不會受到其他分店影響。 > 人手不夠時,就多請人,每個店員可以獨立做不同的工作。 * **程序/行程(Process)**:各個分店。 * **執行緒(Thread)**:店員。**輕量級的執行單位(Light-weight)**。 * **主執行緒(Main Thread)**: 每個程序都會有的那一個最初的店員 有 1 位店員就可以維持最基本的運作。 * **多執行緒(Multithreading)**: 非必要。但人手不夠時,隨時加派店員。 需要的時候存在,不需要的時候被結束:fire:。 ## 多執行緒(Multithreading) ### 多執行緒概念 **執行緒**就像前面例子舉的員工,可以幫我們完成想做的工作。 如果執行緒有好幾個,就像是好幾位店員,可以獨立執行不同的任務,這種情況就是**多執行緒**的概念。 ### 多執行緒非必要,但需要時的確很棒 其實一家分店最低也只要一位店員就可以運作了,但許多的店員分配工作,可以帶來更棒的工作效益。 同理,合理的安排**多緒多工,可以使系統的效能充分發揮**。 ### CPU 主導所有程序與執行緒的執行 概念上,我們認為也希望電腦可以同時執行許多工作,但其實是**CPU在各個程序和執行緒中做切換,順序主要也是由其決定**(CPU分配資源這件事情,還會在這個模組裡面困擾我們很久,請慢慢看下去)。 受到 CPU 資源分配的影響是難免的,畢竟待在同一個硬體環境下,效能是固定且須需要分配的,而電腦中並不是只有我們的程序和執行緒需要工作。 <style> table, tr, td { word-break: break-all; } </style> ## 執行緒與多工 ### 作業系統角度 |比較|合作型(早期)|強奪型(近代)| |-|-|-| |CPU的資源分配|由**程式**主導(易造成獨佔)|由**系統**主導,分配(排程)CPU的使用| |程式的切換|需使用某些系統程序讓程式執行的控制權轉移|可由**系統**中斷工作,切換到另一個工作| ### 程式角度 |比較|Process-based(早期)|Thread-based(近代)| |-|-|-| |工作最小單位|**Program** 是分配送遣的最小單位程式碼|**Thread** 是可被分配送遣的最小單位程式碼| |工作執行數|Process-based 環境下,允許電腦同時執行 2 個以上的工作(**程式**)|Thread-based 環境下,單一程式可以同時執行兩個以上的工作(**執行緒**)| ### 總結 表列總結早期與近代執行緒的特徵與模式: |比較|早期|近代| |-|-|-| |**作業系統角度**|Cooperative multitasking(合作型多工)|Preemptive multitasking(強奪型多工)| |**程式角度**|Process-based multitasking(程序為基礎的多工)|Thread-based multitasking(執行緒為基礎的多工)| ## 執行緒的種類 * 背景執行緒(Daemon Thread) * Garbage Collector<div style="margin-bottom:12px;" title="保持間距用"></div> * 主執行緒(Main Thread): 把 `main()` 方法裡面的程序執行完然後自動關閉。<div style="margin-bottom:12px;" title="保持間距用"></div> * 一般執行緒:<div style="margin-bottom:12px;" title="保持間距用"></div> * **Thread 類別**: <font color=red>需要建立一個類別 extends Thread 類別</font>,並 override 它的 `run()` 方法,此 Thread 的衍生類別產生物件實體後,以 `start()` 呼叫覆寫過的 `run()` 方法。 * **Runnable 介面**: <font color=red>需要建立一個類別 implements Runnable 介面</font>,並實作它的方法 `run()`,此實作 Runnable 的類別產生物件實體後,再傳入 Thread 建構子產生物件,以 `start()` 呼叫實作過的 `run()` 方法。 以下分別說明之。 ## Thread 類別 ### 步驟 1. 建立一個繼承 Thread 類別的新類別(Thread 的[衍生類別](#derived_class))。 2. 衍生類別中 Override Thread 類別的 `run()` 方法(**必須要處理例外**: `try {} catch {}`)。 3. 以衍生類別建造一個物件。 4. 以 `start()` 方法呼叫這個衍生類別物件的 `run()` 方法。 <div id="thread_exception"></div> :::warning **執行緒的例外不能丟出**,只能 `try {} catch {}`。因為基礎類別 Thread 的 `run()` 方法長這樣: <div style="margin-bottom:16px;" title="保持間距用"></div> ```java public void run() {...} ``` 幾個思考與複習:<div style="margin-bottom:16px;" title="保持間距用"></div> 1. 如果 `run()` 方法要把例外丟出去給呼叫自己的 `main()` 方法,需要怎麼做? :::spoiler ------ 點我看 ------ > public void run() <font color=red>throws Exception</font> {...} ::: <div style="margin-bottom:16px;" title="保持間距用"></div> 2. 例外處理和 Override 有沒有關係? :::spoiler ------ 點我看 ------ > 子類別覆寫其父類別定義有 throws 的方法時,子類別所 throws 的 Exception 必須與父類別被覆寫方法的 Exception <font color=red>階層相當或更低階</font>。 > 檢查看看: > (1) 父類別的方法(Thread)有沒有 throws 出例外?<font color=red>沒有。</font> > (2) 子類別的方法(Thread 的衍生類別)想 throws 出的例外有沒有小於父類別的?<font color=red>父類別都已經沒有丟例外出來了,子類別當然不能丟。</font> ::: <div style="margin-bottom:16px;" title="保持間距用"></div> 3. Override 有沒有要求子類別覆寫方法的格式? :::spoiler ------ 點我看 ------ > 必須要和父類別方法的<font color=red>格式一模一樣</font>。 > 再回頭看看,父類別的格式中有沒有 throws 出例外?<font color=red>沒有。</font> ::: ::: ### 衍生類別覆寫方法與測試示範 ```java= public class CounterThread extends Thread { int counter = 10; public void run() { while (counter > 0) { System.out.println(counter); counter--; try { Thread.sleep(1000); //暫停一秒方便觀察 } catch (Exception e) { } } } public static void main(String[] args) { CounterThread ct = new CounterThread(); // 產生執行緒物件 ct.start(); // 呼叫執行緒物件的start()方法 // => start()啟動執行緒 // => start()執行run() } } ``` ## Runnable 介面 執行緒需要先繼承 Thread 類別,才能產生執行緒物件。 但考慮到Java **語法上無法多重繼承**: 1. **已經繼承其他的類別,將無法再繼承 Thread** 2. **沒有繼承任何類別,但想要保留繼承的彈性** <font color=red>**Runnable 介面**</font>提供一個解決方式。 ### 步驟 1. 建立一個實作 Runnable 類別的新類別。 2. 該類別中 `run()` 方法([**必須要處理例外**](#thread_exception): `try {} catch {}`)。 3. 以該 Runnable 類別建造一個物件。 4. 呼叫 Thread 的建構子,傳入該 Runnable 類別的物件,產生一個新的 Thread 物件。 5. 以 `start()` 方法呼叫這個衍生類別物件的 `run()` 方法。 ### 實作方法與測試示範 ```java= public class CounterRunnable implements Runnable { int counter = 10; public void run() { while (counter > 0) { System.out.println(counter); counter--; try { Thread.sleep(1000); //暫停一秒方便觀察 } catch (Exception e) { } } } public static void main(String[] args) { CounterRunnable物件 cr = new CounterRunnable(); // 產生Runnable物件 Thread t = new Thread(cr); // 產生執行緒物件 t.start(); // 呼叫執行緒物件的start()方法 // => start()啟動執行緒 // => start()執行Runnable物件的run() } } ``` ## 執行緒的生命週期(Life Cycle) |狀態|說明| |-|-| |預備狀態(Ready)|執行 `start()`方法即進入排程器中等候 CPU 處理(等候 CPU 呼叫 `run()` 方法)| |~~暫停狀態(Suspended)~~|~~呼叫 `suspend()` 方法使緒程式暫停執行,並可透過 `resume()`方法回到預備狀態~~(過時 API,不建議使用)| |執行狀態(Running)|`run()` 方法被呼叫時| |死亡狀態(Dead)|`run()` 方法執行完、~~`stop()` 方法被呼叫~~(過時 API,不建議使用)| |等待狀態(Waiting)|執行 `wait()` 方法即移出執行狀態,透過被 `notify()`、`notifyAll()` 方法呼叫,回到預備狀態 |睡眠狀態(Sleeping)|取代早期的暫停狀態(Suspeded),停止一段時間後回到預備狀態、`sleep(long milliseconds)`| |阻塞狀態(Block)|需等待一段不確定的硬體輸入、輸出的 I/O 時間,此時將被移出執行狀態| :::warning Java 官方建議<font color=red>**不要再使用**</font> `stop()` 方法,容易使執行緒產生[死結](/@czyue/HJjBJmZ8O#死結(DeadLock))問題,危險性很高(但仍然可以使用)。 ::: ### 生命週期圖解 ![](https://i.imgur.com/hEK0Jhu.png) :::warning 1. 執行緒順序難以預測,因為主控權是在系統和CPU。 2. 執行期間隨時會有切換的狀況發生。 所以很難藉呼叫各種方法和生命週期圖確切掌握切換的狀況。 ::: ## Thread 類別的常用方法 實作Runnable 介面的類別物件,包裝為 Thread 物件後也可以使用。部分方法後面會說明到。 ### 執行執行緒 * `void run()`:以一般非執行緒的方式執行 Thread 物件的 run 方法。 * `void start()`:以執行緒的方式執行 Thread 物件的 run 方法。 ### 執行緒的 setter、getter * `void setName(String name)`:給執行緒一個名字,多個不同執行緒時方便掌握。 * `String getName()` ### 優先權(Priority)的 getter、setter * `void setPriority(int newPriority)`:[設定執行緒的優先權](/@czyue/SkrBq9FEO#setPriority)為 newPriority(有範圍,及定義好的常數)。 * `int getPriority()` ### 生命週期(Life Cycle)相關 * `boolean isAlive()` * `void setDaemon(boolean on)`:設為背景執行緒。 * `boolean isDeamon()`:該執行緒是否為背景執行緒。 * `static Thread currentThread()`:現在是哪個執行緒在執行?將回傳該執行緒物件。 * `void join() throws InterruptedException`:等待被呼叫的執行緒終止,呼叫的(正在執行的)執行緒才會繼續執行。 ### 排程控制相關 * `void join(long milliseconds) throws InterruptedException`:等待至指定毫秒數後,停止等待,加入競爭。 * `static void yield()`:使目前正在執行的執行緒讓出執行權。 * `static void sleep(long milliseconds) throws InterruptedException`:使執行緒休眠至指定毫秒後。 ### [過時APIs](/@czyue/HJjBJmZ8O#過時-API(Deprecation-APIs)): * `void stop()`:終止執行緒。 * `void suspend()`:暫停執行緒。 * `void resume()`:將執行緒從暫停狀態恢復至等待狀態。 * ... :::warning `InterruptedException` 是**一定要處理**的例外。 若是執行緒沒有在規定的毫秒數就被干擾醒來,就會發生此例外(不太常見)。 ::: ## 註解 不希望放錯重點的註解放在這: 1. <span id="derived_class">衍生類別</span>:可以當作是子類別,父類別在此相對名稱為「基礎類別」。 ## 參考資料 1. [衍生類別與物件](http://epaper.gotop.com.tw/PDFSample/ACL034500.pdf) 2. [繼承 Inheritance](https://www.csie.ntu.edu.tw/~r95116/CA200/slide/C2_Inheritance.pdf) --- * 執行緒 * 單執行緒 * 多執行緒 * Thread 類別 * `run()` 方法; * 只能用 `try {} catch {}` 接住的例外(不能在方法丟出) * 保留繼承的彈性:Runable 介面 * 以 `start()` 呼叫 Thread物件的 `run()` 方法 * 例外一樣只能接住 * 執行緒順序控制 * `yield()` 方法 * `join()` 方法 * `setPriority()` 方法 * 同步化 * Synchronized 介面 * `synchronized` 關鍵字 * 執行緒間的等待與通知 * `wait()` * `notify()` 與 `notifyAll()` * DeadLock * 哲學家就餐

    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