start():請求 JVM 分配新線程,**異步**執行 run();run():普通方法調用,**同步**在當前線程執行,不會開啟新線程。public class ThreadDemo1 extends Thread {
private final String msg;
private final int count;
public ThreadDemo1(String msg, int count) {
this.msg = msg; this.count = count;
setName(msg + "-Runner");
}
@Override public void run() {
while (count-- > 0) {
System.out.println(msg);
sleepQuietly(100);
}
System.out.println(msg + " all done.");
}
private void sleepQuietly(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException ignored) {}
}
public static void main(String[] args) {
new ThreadDemo1("Hello from X", 10).start();
new ThreadDemo1("Hello from Y", 15).start();
}
}
public class ThreadDemo2 implements Runnable {
private final String msg;
private final int count;
public ThreadDemo2(String msg, int count) {
this.msg = msg; this.count = count;
new Thread(this, msg + "-Runner").start();
}
@Override public void run() {
while (count-- > 0) {
System.out.println(msg);
sleepQuietly(100);
}
System.out.println(msg + " all done.");
}
// main 同方式一
}
優勢:避免單繼承限制,邏輯與線程控制解耦,易於提交給線程池。
public class ThreadDemo3 {
public static void main(String[] args) {
// 匿名類
new Thread(new Runnable() {
@Override public void run() { /* ... */ }
}, "Anon-Runner").start();
// Lambda(函數式介面)
new Thread(() -> {
for (int i = 10; i > 0; i--) {
System.out.println("Lambda: " + i);
sleepQuietly(100);
}
}, "Lambda-Runner").start();
}
// sleepQuietly 同前
}
Hello from X Hello from Y Hello from X Hello from Y ... Hello from X all done. Hello from Y all done.
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> { /* task */ });
pool.shutdown();
Future/CompletableFuture 獲取結果。| 錯誤寫法 | 後果 | 正確寫法 |
|---|---|---|
new MyThread().run() | 主線程同步執行,無併發 | new MyThread().start() |
在 run() 內死循環無 sleep | 佔用 CPU 100%,導致饑餓 | 加 Thread.sleep 或 wait/notify |
| 共享變量無同步 | 數據競爭、可見性問題 | volatile/AtomicInteger/synchronized |