public class MyFirstThread extends Thread {
public void run() { /* 執行緒本體 */ }
}
Thread 在 java.lang,無需 import。run() 放入執行碼。new MyFirstThread().start();(start() 會呼叫 run() 在新執行緒執行)。stop()、suspend()、resume()(已棄用)。public class ComplexThread extends Thread {
private int delay;
ComplexThread(String name, float seconds) {
super(name);
delay = (int) (seconds * 1000);
start(); // 自動啟動
}
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
try { Thread.sleep(delay); }
catch (InterruptedException e) { return; }
}
}
public static void main(String[] argv) {
new ComplexThread("one potato", 1.1f);
new ComplexThread("two potato", 1.3f);
new ComplexThread("three potato", 0.5f);
new ComplexThread("four", 0.7f);
}
}
public class MySecondThread extends ImportantClass implements Runnable {
public void run() { ... }
}
Runnable 表示意圖在獨立執行緒執行(Thread 本身也實作 Runnable)。run()。MySecondThread mst = new MySecondThread();
Thread t = new Thread(mst);
t.start();
Thread(Runnable target) 建構子。t.start() 呼叫 target.run()。try { myThread.start(); }
catch (ThreadDeath td) {
System.out.println("end Thread");
throw td; // 重拋讓 JVM 執行清理
}
MIN_PRIORITY=1、NORM_PRIORITY=5、MAX_PRIORITY=10。預設 NORM_PRIORITY。run() 中呼叫 Thread.yield() 或 Thread.sleep() 讓出 CPU。setPriority() 可動態調整:t1.setPriority(t2.getPriority() + 1)。join():等待指定執行緒結束。try { t.join(); } catch (InterruptedException e) {}public synchronized void countMe() {
crucialValue += 1; // 三步驟變原子操作
}
synchronized(p) {
safeX = p.x();
safeY = p.y(); // 區塊期間 p 不可被其他執行緒修改
}
public class StaticCounter {
private static int crucialValue;
public void countMe() {
synchronized (getClass()) { // 或 Class.forName("StaticCounter")
crucialValue += 1;
}
}
}
getClass() 或 Class.forName() 取得 Class 物件,不可直接用類別名稱。新建 → 就緒 → 執行 → 阻塞/等待/睡眠 → 結束。yield() 讓出 CPU 回就緒態;sleep() 進入計時等待;wait()/notify() 配合物件鎖進行協調(屬於 Object 方法)。