繼承 Thread 類別
public class ThreadA extends Thread {
public void run() {
System.out.println("A");
}
}
執行
Thread a = new ThreadA();
a.start();
實作 Runnable 介面
public class ThreadB implements Runnable {
public void run() {
System.out.println("B");
}
}
執行
Thread b = new Thread(new ThreadB());
b.start();
匿名內部類別
new Thread(new Runnable() {
public void run() {
System.out.println("C");
}
}).start();
// Lambda
new Thread(() -> {
System.out.println("D");
}).start();
Thread Pool
節省效能
ExecutorService ex = Executors.newSingleThreadExecutor();
ex.execute(new Runnable() {
public void run() {
System.out.println("E");
}
});
ex.shutdown(); //要記得關閉