Thread 類別Runnable 介面(推薦):職責分離,避免單一繼承限制,方便傳入執行緒池。Runnable 的類別,覆寫 run()。Thread 建構子參數。Thread.start() 啟動執行緒(切勿直接呼叫 run())。
package mythread;
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
MyRunnable task1 = new MyRunnable();
MyRunnable task2 = new MyRunnable();
Thread t1 = new Thread(task1, "MyThread-1");
Thread t2 = new Thread(task2); // 預設名稱 Thread-0, Thread-1...
t2.setName("MyThread-2");
t1.start();
t2.start();
}
}
MyThread-1
MyThread-2
Thread.currentThread().getName() 取得正在執行的執行緒名稱。Thread(Runnable target, String name) 可一次指定任務與名稱。setName() 可在 start() 前後修改,但 start() 後改名有競態風險,建議建構時指定。Runnable 實例可傳入多個 Thread,共享任務邏輯與狀態。
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(new MyRunnable()); // 自動管理執行緒生命週期
pool.shutdown();
實務上極少直接 new Thread(),統一交給 ExecutorService 管理。