線程是進程內部的順序控制流。一個進程對應一個任務,線程則是任務中的一條執行路徑。多進程指操作系統同時運行多個程序;多線程指同一應用內多條執行路徑並發。Java 通過 java.lang.Thread 實現線程,JVM 啟動時創建主線程(執行 main()),新線程通過 Thread 實例的 run() 方法執行,調用 start() 啟動。
Runnable,實現 run() 定義線程體。Thread t = new Thread(runnableTarget);Runnable 實例的數據。Thread.currentThread() 獲取當前線程引用。class MyThread extends Thread {
public void run() { ... }
}
MyThread t = new MyThread();
| 方法 | 說明 |
|---|---|
isAlive() | 判斷線程是否存活 |
getPriority() / setPriority() | 獲取/設置優先級(1-10) |
sleep() | 當前線程休眠指定毫秒 |
join() | 等待該線程終止 |
yield() | 讓出 CPU,進入就緒隊列 |
wait() | 進入對象等待池,釋放鎖 |
notify()/notifyAll() | 喚醒等待池中一個/所有線程 |
使用 synchronized、wait()、notify() 實現線程安全的緩衝區:
class ProductBox {
Product[] box = new Product[6];
int index = 0;
public synchronized void push(Product p) {
while (index == box.length) {
try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }
}
notify();
box[index++] = p;
}
public synchronized Product pop() {
while (index == 0) {
try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }
}
notify();
return box[--index];
}
}
Producer 與 Consumer 實現 Runnable,共享 ProductBox 實例,通過 wait/notify 協作。主程序啟動兩線程,設置生產者優先級較高演示調度效果。
synchronized 方法鎖 this;靜態方法鎖 Class 對象;代碼塊可指定任意對象。IllegalMonitorStateException。java.util.concurrent 包(BlockingQueue、ReentrantLock 等)替代底層同步。