java 創造執行緒 Thread 的三種方法
阿新 • • 發佈:2019-02-05
發現 java 的不少例子中都涉及到執行緒,看來執行緒是 java 蠻重要的一部分的。
但最近看 執行緒 的一些講解時,覺得並不是很好理解,有點抽象。
邊看邊總結吧。 最近查閱到:java 程式設計一般情況下用不到多執行緒。多執行緒一般在開發 web 時 用到。
執行執行緒用 start() 方法,而 start() 將呼叫執行緒中的 run() 方法。
一. 創造一個執行緒
三種方法:1. 繼承 Thread 類並重寫 run 方法
舉例:注意:重寫的 run() 方法必須為 public.public class HelloWorld extends Thread{ @Override public void run(){ System.out.println("Hello World"); } public static void main(String []args){ new HelloWorld().start(); } }
2. 匯入一個 Runnable 介面
舉例:此時可以用 lambda 函式定義 Runnable 介面public class HelloWorld{
public static void main(String []args){
Runnable t=()->System.out.println("Hello World");
Thread myThread=new Thread(t);
myThread.start();
}
}
3. 使用方法引用
java 8 之後才有這個功能,如果方法沒有呼叫變數,沒有返回值,則可以使用方法引用生成Thread。 舉例:注意: 方法必須為 static.public class HelloWorld{ static void print(){ System.out.println("Hello World"); } public static void main(String []args){ new Thread(HelloWorld::print).start(); } }