死磕 java執行緒系列之建立執行緒的8種方式
問題
(1)建立執行緒有哪幾種方式?
(2)它們分別有什麼運用場景?
簡介
建立執行緒,是多執行緒程式設計中最基本的操作,彤哥總結了一下,大概有8種建立執行緒的方式,你知道嗎?
繼承Thread類並重寫run()方法
public class CreatingThread01 extends Thread { @Override public void run() { System.out.println(getName() + " is running"); } public static void main(String[] args) { new CreatingThread01().start(); new CreatingThread01().start(); new CreatingThread01().start(); new CreatingThread01().start(); } }
繼承Thread類並重寫run()方法,這種方式的弊端是一個類只能繼承一個父類,如果這個類本身已經繼承了其它類,就不能使用這種方式了。
實現Runnable介面
public class CreatingThread02 implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running"); } public static void main(String[] args) { new Thread(new CreatingThread02()).start(); new Thread(new CreatingThread02()).start(); new Thread(new CreatingThread02()).start(); new Thread(new CreatingThread02()).start(); } }
實現Runnable介面,這種方式的好處是一個類可以實現多個介面,不影響其繼承體系。
匿名內部類
public class CreatingThread03 { public static void main(String[] args) { // Thread匿名類,重寫Thread的run()方法 new Thread() { @Override public void run() { System.out.println(getName() + " is running"); } }.start(); // Runnable匿名類,實現其run()方法 new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running"); } }).start(); // 同上,使用lambda表示式函數語言程式設計 new Thread(()->{ System.out.println(Thread.currentThread().getName() + " is running"); }).start(); } }
使用匿名類的方式,一是重寫Thread的run()方法,二是傳入Runnable的匿名類,三是使用lambda方式,現在一般使用第三種(java8+),簡單快捷。
實現Callabe介面
public class CreatingThread04 implements Callable<long> {
@Override
public Long call() throws Exception {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getId() + " is running");
return Thread.currentThread().getId();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<long> task = new FutureTask<>(new CreatingThread04());
new Thread(task).start();
System.out.println("等待完成任務");
Long result = task.get();
System.out.println("任務結果:" + result);
}
}
實現Callabe介面,可以獲取執行緒執行的結果,FutureTask實際上實現了Runnable介面。
定時器(java.util.Timer)
public class CreatingThread05 {
public static void main(String[] args) {
Timer timer = new Timer();
// 每隔1秒執行一次
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}, 0 , 1000);
}
}
使用定時器java.util.Timer可以快速地實現定時任務,TimerTask實際上實現了Runnable介面。
執行緒池
public class CreatingThread06 {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 100; i++) {
threadPool.execute(()-> System.out.println(Thread.currentThread().getName() + " is running"));
}
}
}
使用執行緒池的方式,可以複用執行緒,節約系統資源。
平行計算(Java8+)
public class CreatingThread07 {
public static void main(String[] args) {
List<integer> list = Arrays.asList(1, 2, 3, 4, 5);
// 序列,列印結果為12345
list.stream().forEach(System.out::print);
System.out.println();
// 並行,列印結果隨機,比如35214
list.parallelStream().forEach(System.out::print);
}
}
使用平行計算的方式,可以提高程式執行的效率,多執行緒並行執行。
Spring非同步方法
首先,springboot啟動類加上@EnableAsync
註解(@EnableAsync是spring支援的,這裡方便舉例使用springboot)。
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
其次,方法加上@Async
註解。
@Service
public class CreatingThread08Service {
@Async
public void call() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}
然後,測試用例直接跟使用一般的Service方法一模一樣。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class CreatingThread08Test {
@Autowired
private CreatingThread08Service creatingThread08Service;
@Test
public void test() {
creatingThread08Service.call();
creatingThread08Service.call();
creatingThread08Service.call();
creatingThread08Service.call();
}
}
執行結果如下:
task-3 is running
task-2 is running
task-1 is running
task-4 is running
可以看到每次執行方法時使用的執行緒都不一樣。
使用Spring非同步方法的方式,可以說是相當地方便,適用於前後邏輯不相關聯的適合用非同步呼叫的一些方法,比如傳送簡訊的功能。
總結
(1)繼承Thread類並重寫run()方法;
(2)實現Runnable介面;
(3)匿名內部類;
(4)實現Callabe介面;
(5)定時器(java.util.Timer);
(6)執行緒池;
(7)平行計算(Java8+);
(8)Spring非同步方法;
彩蛋
上面介紹了那麼多建立執行緒的方式,其實本質上就兩種,一種是繼承Thread類並重寫其run()方法,一種是實現Runnable介面的run()方法,那麼它們之間到底有什麼聯絡呢?
請看下面的例子,同時繼承Thread並實現Runnable介面,應該輸出什麼呢?
public class CreatingThread09 {
public static void main(String[] args) {
new Thread(()-> {
System.out.println("Runnable: " + Thread.currentThread().getName());
}) {
@Override
public void run() {
System.out.println("Thread: " + getName());
}
}.start();
}
}
說到這裡,我們有必要看一下Thread類的原始碼:
public class Thread implements Runnable {
// Thread維護了一個Runnable的例項
private Runnable target;
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
// ...
// 構造方法傳進來的Runnable會賦值給target
this.target = target;
// ...
}
@Override
public void run() {
// Thread預設的run()方法,如果target不為空,會執行target的run()方法
if (target != null) {
target.run();
}
}
}
看到這裡是不是豁然開朗呢?既然上面的例子同時繼承Thread並實現了Runnable介面,根據原始碼,實際上相當於重寫了Thread的run()方法,在Thread的run()方法時實際上跟target都沒有關係了。
所以,上面的例子輸出結果為Thread: Thread-0
,只輸出重寫Thread的run()方法中的內容。
歡迎關注我的公眾號“彤哥讀原始碼”,檢視更多原始碼系列文章, 與彤哥一起暢遊原始碼的海洋。
</integer></