Runnable 接口創建線程兩步走
- 實現
Runnable 接口,重寫 run()
- 創建
Thread 實例,構造器傳入 Runnable 實例
- 調用
Thread.start() 啟動線程
代碼示例
public class MyRunnable implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
MyRunnable t1 = new MyRunnable();
MyRunnable t2 = new MyRunnable();
Thread thread1 = new Thread(t1, "MyThread1");
Thread thread2 = new Thread(t2);
thread2.setName("MyThread2");
thread1.start();
thread2.start();
}
}
運行結果
MyThread1
MyThread2
核心要點
Thread 實現了 Runnable,所以 Thread 子類實例也可作為 target
- 線程名可通過構造器或
setName() 設置
- 必須調用
start() 而非直接調用 run() (後者為主線程同步執行)