class MyThread extends Thread {
public void run() { /* 執行邏輯 */ }
}
// 使用
MyThread t1 = new MyThread();
t1.start();
class MyTask implements Runnable {
private int ticket = 100; // 共享資源
public void run() { /* 存取 ticket */ }
}
// 使用:同一任務實例建立多個執行緒
MyTask task = new MyTask();
new Thread(task, "Window-1").start();
new Thread(task, "Window-2").start();
new Thread(task, "Window-3").start();
class MyTask implements Runnable {
private Thread t;
MyTask(String name) { t = new Thread(this, name); }
public void start() { t.start(); }
public void run() { /* ... */ }
}
MIN_PRIORITY(1) ~ MAX_PRIORITY(10),預設 NORM_PRIORITY(5)。setPriority(int)、getPriority() 動態調整。Thread t1 = new Thread(() -> { while(running) count1++; }, "Low");
Thread t2 = new Thread(() -> { while(running) count2++; }, "High");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start(); t2.start();
Thread.sleep(1000);
running = false;
System.out.println("Low: " + count1 + ", High: " + count2); // High 顯著較大
yield() 主動讓出 CPU(同優先級)。ExecutorService + ThreadFactory 統一管理優先級。ReentrantLock 公平鎖或即時作業系統(RTSJ)。實作 Runnable 是建立執行緒的主流範式,支援資源共享與解耦。優先級僅為排程「提示」,不可作為正確性保證;生產環境請改用高階並發套件(java.util.concurrent)。