Java中創(chuàng)建線程的四種方式的最佳實(shí)踐
一句話結(jié)論
能不用 new Thread() 就別直接用;企業(yè)級(jí)項(xiàng)目首選線程池,避免資源耗盡與管理混亂。
一、方式一:繼承 Thread 類
示例
class MyThread extends Thread {
@Override
public void run() {
System.out.println("任務(wù)執(zhí)行:" + Thread.currentThread().getName());
}
}
public class Demo {
public static void main(String[] args) {
new MyThread().start();
}
}
特點(diǎn)
優(yōu)點(diǎn):實(shí)現(xiàn)簡單,直接繼承并重寫 run() 方法。
缺點(diǎn):
- Java 單繼承限制,無法再繼承其他類。
- 任務(wù)和線程強(qiáng)耦合,任務(wù)不能復(fù)用。
- 線程創(chuàng)建和銷毀開銷大。
結(jié)論:只適合入門學(xué)習(xí),生產(chǎn)代碼中幾乎不用。
二、方式二:實(shí)現(xiàn) Runnable 接口
示例
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("任務(wù)執(zhí)行:" + Thread.currentThread().getName());
}
}
public class Demo {
public static void main(String[] args) {
new Thread(new MyRunnable()).start();
}
}
特點(diǎn)
優(yōu)點(diǎn):
- 任務(wù)與線程解耦,可以復(fù)用
Runnable對(duì)象。 - 避免單繼承限制,更靈活。
缺點(diǎn):
run() 無返回值,無法獲取執(zhí)行結(jié)果。
結(jié)論:實(shí)際項(xiàng)目常用,但當(dāng)需要返回值或異常處理時(shí)局限性明顯。
三、方式三:實(shí)現(xiàn) Callable 接口 + Future
示例
import java.util.concurrent.*;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() {
return 42;
}
}
public class Demo {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
System.out.println("結(jié)果:" + future.get());
executor.shutdown();
}
}
特點(diǎn)
優(yōu)點(diǎn):
call()方法有返回值,可以拋出異常。- 搭配
Future、CompletableFuture支持異步編排。
缺點(diǎn):
相比 Runnable 更復(fù)雜,需要 ExecutorService 配合。
結(jié)論:適合需要獲取結(jié)果或異常處理的異步任務(wù)。
四、方式四:使用線程池(Executor 框架)
示例
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 5; i++) {
pool.execute(() -> System.out.println(Thread.currentThread().getName() + " 執(zhí)行任務(wù)"));
}
pool.shutdown();
特點(diǎn)
優(yōu)點(diǎn):
- 資源復(fù)用:避免頻繁創(chuàng)建/銷毀線程。
- 任務(wù)調(diào)度:隊(duì)列 + 拒絕策略,適合高并發(fā)場景。
- 靈活擴(kuò)展:可自定義核心線程數(shù)、最大線程數(shù)、存活時(shí)間、隊(duì)列。
缺點(diǎn):
- 使用不當(dāng)可能導(dǎo)致隊(duì)列堆積、拒絕任務(wù)或 OOM。
- 需配合監(jiān)控與合理參數(shù)配置。
結(jié)論:企業(yè)級(jí)項(xiàng)目首選,尤其是高并發(fā)系統(tǒng)。
五、四種方式對(duì)比表
| 方式 | 返回值 | 靈活性 | 使用難度 | 適用場景 |
|---|---|---|---|---|
| 繼承 Thread | 無 | 低 | 簡單 | 學(xué)習(xí)/測(cè)試 |
| Runnable | 無 | 中 | 簡單 | 一次性異步任務(wù) |
| Callable + Future | 有 | 高 | 中等 | 需要結(jié)果/異常處理 |
| 線程池 | 可選(Future) | 很高 | 較高 | 生產(chǎn)環(huán)境標(biāo)準(zhǔn)方案 |
六、工程實(shí)踐建議
禁止直接 new Thread,無法控制線程數(shù)量,容易耗盡資源。
避免 Executors 提供的快捷工廠方法(如 newFixedThreadPool),因其參數(shù)不透明,可能造成隱患。推薦顯式使用 ThreadPoolExecutor 構(gòu)造函數(shù),明確核心參數(shù)與拒絕策略。
推薦使用 Callable + 線程池,既能拿到返回值,也能進(jìn)行任務(wù)調(diào)度與統(tǒng)一管理。
務(wù)必優(yōu)雅關(guān)閉線程池,否則可能引發(fā)內(nèi)存泄漏或服務(wù)無法退出。
七、小結(jié)
- 繼承 Thread:入門。
- Runnable:任務(wù)解耦,輕量。
- Callable:有返回值,實(shí)用。
- 線程池:工程實(shí)踐必選,結(jié)合
Future/CompletableFuture更強(qiáng)大。
到此這篇關(guān)于Java中創(chuàng)建線程的四種方式的最佳實(shí)踐的文章就介紹到這了,更多相關(guān)Java創(chuàng)建線程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
老生常談設(shè)計(jì)模式之動(dòng)態(tài)代理
下面小編就為大家?guī)硪黄仙U勗O(shè)計(jì)模式之動(dòng)態(tài)代理。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
Springboot如何去掉URL后面的jsessionid
這篇文章主要介紹了Springboot如何去掉URL后面的jsessionid,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Springboot整合SpringSecurity實(shí)現(xiàn)登錄認(rèn)證和鑒權(quán)全過程
這篇文章主要介紹了Springboot整合SpringSecurity實(shí)現(xiàn)登錄認(rèn)證和鑒權(quán)全過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
JVM生產(chǎn)環(huán)境調(diào)優(yōu)實(shí)戰(zhàn)案例講解
這篇文章主要介紹了JVM生產(chǎn)環(huán)境調(diào)優(yōu)實(shí)戰(zhàn),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2025-04-04
記一次Feign中實(shí)現(xiàn)傳實(shí)體Bean的問題
這篇文章主要介紹了記一次Feign中如何傳實(shí)體Bean的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot Maven打包如何根據(jù)環(huán)境排除文件
文章介紹了在SpringBoot項(xiàng)目中,根據(jù)不同的環(huán)境(開發(fā)、測(cè)試、生產(chǎn))進(jìn)行JSP文件打包處理的方法,通過配置`pom.xml`文件中的``標(biāo)簽,可以實(shí)現(xiàn)開發(fā)環(huán)境保留`index.jsp`文件,測(cè)試環(huán)境和生產(chǎn)環(huán)境排除該文件2024-12-12

