Java 內建支援多線程,一個多線程程式包含兩個以上可並發執行的部分,每部分稱為一個線程,定義獨立執行路徑。多線程是多任務的特殊形式,資源開銷較小,能充分利用 CPU 效能。

| 狀態 | 說明 |
|---|---|
| 新建 | new Thread() 建立物件,尚未呼叫 start() |
| 就緒 | 呼叫 start() 後進入就緒佇列,等待 JVM 排程器調度 |
| 執行 | 獲得 CPU 資源,執行 run();可轉為阻塞、就緒或死亡 |
| 阻塞 | 執行 sleep()、wait()、同步鎖失敗、I/O 請求等;條件滿足後回就緒 |
| 死亡 | run() 完成或異常終止 |
阻塞細分:等待阻塞(wait())、同步阻塞(synchronized 鎖失敗)、其他阻塞(sleep()、join()、I/O)。
MIN_PRIORITY)~ 10(MAX_PRIORITY),預設 5(NORM_PRIORITY)class RunnableDemo implements Runnable {
private Thread t; private String threadName;
RunnableDemo(String name) { threadName = name; System.out.println("Creating " + threadName); }
public void run() {
System.out.println("Running " + threadName);
try { for (int i=4; i>0; i--) { System.out.println("Thread: " + threadName + ", " + i); Thread.sleep(50); } }
catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); }
System.out.println("Thread " + threadName + " exiting.");
}
public void start() { if (t==null) { t = new Thread(this, threadName); t.start(); } }
}
public class TestThread {
public static void main(String[] args) {
new RunnableDemo("Thread-1").start();
new RunnableDemo("Thread-2").start();
}
}
class ThreadDemo extends Thread {
// 結構類似 RunnableDemo,但繼承 Thread
// 本質上仍是實作 Runnable
}
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args) {
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for (int i=0; i<100; i++) {
System.out.println(Thread.currentThread().getName() + " 的迴圈變數 i=" + i);
if (i==20) new Thread(ft, "有回傳值的線程").start();
}
try { System.out.println("子線程回傳值:" + ft.get()); }
catch (Exception e) { e.printStackTrace(); }
}
@Override public Integer call() throws Exception {
int i=0; for (; i<100; i++) System.out.println(Thread.currentThread().getName() + " " + i);
return i;
}
}
| 方法 | 說明 |
|---|---|
start() | 啟動線程,JVM 呼叫 run() |
run() | 線程執行主體 |
setName(String) | 設定線程名稱 |
setPriority(int) | 設定優先級 |
setDaemon(boolean) | 標記守護/用戶線程 |
join(long ms) | 等待線程終止(最長 ms 毫秒) |
interrupt() | 中斷線程 |
isAlive() | 檢測是否存活 |
靜態方法:yield()、sleep(ms)、holdsLock(obj)、currentThread()、dumpStack()。
this 即為目前線程,無需呼叫 Thread.currentThread()