Java 有兩種建立多執行緒的方式:繼承 Thread 類別,或實作 Runnable 介面。要用哪種?最直接的答案是拿實際問題跑一遍。以下用「四個售票點銷售同一趟列車的 100 張票」來做實驗。
public class ThreadDemo1 {
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
t.start();
t.start();
t.start();
t.start();
}
}
class ThreadTest extends Thread {
private int ticket = 100;
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName()
+ " is saling ticket " + ticket--);
} else {
break;
}
}
}
}
結果只有一個執行緒在跑。結論:一個 Thread 物件只能啟動一個執行緒,start() 呼叫多少次都一樣(多呼叫還會拋 IllegalThreadStateException)。
public class ThreadDemo1 {
public static void main(String[] args) {
new ThreadTest().start();
new ThreadTest().start();
new ThreadTest().start();
new ThreadTest().start();
}
}
這次每個票號都被印了四次——四個執行緒各自賣各自的 100 張票,賣的根本不是同一批資源。原因很直白:我們建了四個 ThreadTest 物件,等於有了四份資源,每個執行緒都在處理自己那一份。
需求要求的是:一份資源、多個執行緒、執行同一段程式碼。
public class ThreadDemo1 {
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class ThreadTest implements Runnable {
private int tickets = 100;
public void run() {
while (true) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName()
+ " is saling ticket " + tickets--);
}
}
}
}
這裡四個執行緒呼叫的是同一個 ThreadTest 物件的 run(),存取的是同一份 tickets——正如 Windows 上可以開啟多個記事本視窗,但用的是同一份程式碼。
補充一點實務上的注意:上面三個範例都沒有做同步,票數其實會出現重複或跳號——這正說明「能共用資源」與「共用得安全」是兩件事,真要上 production,synchronized 或 AtomicInteger 是必須補上的一環。