本例演示最基礎的多線程創建模式:主線程循環創建 5 個子線程,每個線程通過構造器參數區分身份,運行短暫任務後結束。
public class multiThread {
public static void main(String[] args) { new multiThread(); }
multiThread() {
for (int i = 0; i < 5; i++) {
System.out.println("Creating thread " + i);
innThread mt = new innThread(i);
mt.start(); // 啟動線程,異步執行 run()
}
}
class innThread extends Thread {
int count;
innThread(int i) { count = i; }
public void run() {
System.out.println("now " + count + " thread is beginning..... ");
try { sleep(10 - count); } catch (Exception e) { System.out.println(e); }
System.out.println("\n" + count + " thread is end!");
}
}
}
run() 作為線程執行體start() 創建新線程並調用 run();直接調用 run() 只在當前線程同步執行super("名稱") 或 setName() 便於調試// 1. Lambda + Thread(Java 8+)
for (int i = 0; i < 5; i++) {
final int id = i;
new Thread(() -> {
System.out.println("Thread " + id + " starting");
try { Thread.sleep(10 - id); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
System.out.println("Thread " + id + " ended");
}, "Worker-" + id).start();
}
// 2. ExecutorService(生產環境推薦)
ExecutorService pool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
final int id = i;
pool.submit(() -> {
System.out.println("Thread " + id + " starting");
try { Thread.sleep(10 - id); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
System.out.println("Thread " + id + " ended");
});
}
pool.shutdown();