當需要在不同程式功能之間,互不影響的前提下同時執行就可使用 Therad --- # 多執行緒的寫法 ### 實例 Thread Object 最基本的寫法,後續寫法亦不離 `Thread (Runnable {run})` 這個格式 ```java public class Example { Thread thread = null; public Example(String message) { thread = new Thread(new Runnable() { @Override public void run() { System.out.println("Hello " + message); } }); } } public class Test { public static void main(String args[]) { Example example = new Example("World!"); example.thread.start(); } } ``` ### 繼承 Thread Class Thread Class 將執行緒的工作放在 run() 方法中,所以可以直接覆寫該方法來實作功能 ```java public class ThreadExample extends Thread { private String message = ""; public ThreadExample(String message) { this.message = message; } public void run() { System.out.println("Hello " + this.message); } } public class Test { public static void main(String args[]) { ThreadExample th_example = new ThreadExample("World!"); th_example.start(); } } ``` ### 實作 Runnable Interface Runnable 介面只包含一個方法:run() 因此 Thread Class 可改由該介面來實作功能,在開發上有較高的擴充性 ```java public class RunnableExample implements Runnable { private String message = ""; public RunnableExample(String message) { this.message = message; } @Override public void run() { System.out.println("Hello " + this.message); } } public class Test { public static void main(String args[]) { RunnableExample run_example = new RunnableExample("World!"); Thread thread = new Thread(run_example); thread.start(); } } ``` --- > #參考資料 > [Day3:寫簡單 Java Thread Sample Code (一)](https://ithelp.ithome.com.tw/articles/10202277) > [Java 的多執行緒,以賽馬為例,如何繼承 Thread 與實作 Runnable 介面](https://litotom.com/2020/07/11/java-thread-runnable/)
×
Sign in
Email
Password
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