本例演示通過實現 Runnable 接口創建線程:主線程構造 Thread(this, name) 將自身作為任務傳入,啟動子線程並發執行。
public class twothread implements Runnable {
twothread() {
Thread t1 = Thread.currentThread();
t1.setName("The first main thread");
System.out.println("The running thread: " + t1);
Thread t2 = new Thread(this, "the second thread");
System.out.println("creat another thread");
t2.start();
try {
System.out.println("first thread will sleep");
Thread.sleep(3000);
} catch (InterruptedException e) { System.out.println("first thread has wrong"); }
System.out.println("first thread exit");
}
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Sleep time for thread 2: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) { System.out.println("thread has wrong"); }
System.out.println("second thread exit");
}
public static void main(String args[]) { new twothread(); }
}
| 維度 | 繼承 Thread | 實現 Runnable |
|---|---|---|
| 繼承限制 | 單繼承,無法繼承其他類 | 無限制,可繼承任意類 |
| 任務與線程 | 耦合(類即線程) | 分離(任務可被多線程執行) |
| 共享數據 | 需額外傳遞 | 自然共享 this 實例字段 | 線程池適配 | 不直接支援 | 完美支援 ExecutorService.submit(Runnable) |
| Lambda 支援 | 不支援 | 函數式接口,完美支援 Lambda |
Runnable task = new MyTask(); new Thread(task, "T1").start(); new Thread(task, "T2").start(); // 同一任務實例被多線程執行 executor.submit(task); // 線程池執行
Runnable r = () -> { ... };executor.submit(runnable)Future future = executor.submit(callable) start() 方法Thread.sleep() 捕獲 InterruptedException 應重設置中斷標誌:Thread.currentThread().interrupt()