一冤留、基本概念
1.什么是進(jìn)程?
電腦中會有很多單獨運行的程序树灶,每個程序有一個獨立的進(jìn)程纤怒,而進(jìn)程之間是相互獨立存在的。
例如圖中的微信天通、Chrome泊窘、idea等等。
2.什么是線程像寒?
進(jìn)程想要執(zhí)行任務(wù)就需要依賴線程烘豹。
進(jìn)程中的最小執(zhí)行單位就是線程,并且一個進(jìn)程中至少有一個線程诺祸。
補(bǔ)充:Java中有默認(rèn)有幾個線程携悯?兩個:main、gc
那什么又是多線程呢筷笨?
提到多線程這里要說兩個概念憔鬼,就是串行和并行,搞清楚這個胃夏,我們才能更好地理解多線程。
串行:
并行:
二、線程的創(chuàng)建
Java 提供了三種創(chuàng)建線程的方法:
// 通過繼承 Thread 類本身
public class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
//實例化自定義的線程
Thread t = new MyThread("thread-aa");
//啟動線程
t.start();
}
}
Output:
thread-aa
Process finished with exit code 0
// 或使用匿名內(nèi)部類
public class MyThread {
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
thread.start();
}
}
// 通過實現(xiàn) Runnable 接口
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args){
Runnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
// 通過 Callable 和 Future 創(chuàng)建線程
public class MyCallable implements Callable {
@Override
public String call() {
System.out.println(Thread.currentThread().getName());
return "有返回值答恶。";
}
public static void main(String[] args){
MyCallable myCallable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<>(myCallable);
//傳入線程執(zhí)行目標(biāo)悬嗓,實例化線程對象
Thread t = new Thread(futureTask);
t.start();
try {
String r = futureTask.get();
System.out.println(r);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
三污呼、CompletableFuture
1. 概述
CompletableFuture是 Java 8 中引入的一個類
它實現(xiàn)了CompletionStage接口,提供了一組豐富的方法來處理異步操作和多個任務(wù)的結(jié)果曙求。
它支持鏈?zhǔn)讲僮?/strong>悟狱,可以方便地處理任務(wù)的依賴關(guān)系和結(jié)果轉(zhuǎn)換挤渐。
相比于傳統(tǒng)的Future接口双絮,CompletableFuture更加靈活和強(qiáng)大。
CompletableFuture的使用具有以下優(yōu)勢和特點:
- 異步執(zhí)行:CompletableFuture允許任務(wù)在后臺線程中異步執(zhí)行宫纬,不會阻塞主線程漓骚,提高了應(yīng)用程序的響應(yīng)性和性能蝌蹂。
- 鏈?zhǔn)讲僮鳎和ㄟ^CompletableFuture提供的方法孤个,可以方便地對任務(wù)進(jìn)行鏈?zhǔn)讲僮髌肜穑瑯?gòu)建復(fù)雜的任務(wù)依賴關(guān)系佳遂,實現(xiàn)高效的任務(wù)調(diào)度和執(zhí)行。
- 異常處理:CompletableFuture提供了豐富的異常處理方法凤壁,可以處理任務(wù)執(zhí)行過程中可能發(fā)生的異常拧抖,并實現(xiàn)靈活的錯誤處理和回退機(jī)制唧席。
- 多任務(wù)組合:CompletableFuture支持多個任務(wù)的并發(fā)執(zhí)行和結(jié)果組合淌哟⊥讲郑可以輕松地實現(xiàn)多任務(wù)并發(fā)處理的場景掉弛,提高應(yīng)用程序的效率和并發(fā)性殃饿。
2. 具體使用網(wǎng)上有很多文檔
個人覺得這種方式最優(yōu)雅乎芳,也是我最常使用的秒咐。
public class TestCompletableFuture {
public static void main(String[] args) {
CompletableFuture.runAsync(() -> System.out.println(Thread.currentThread().getName() + " 1")).join();
}
}
3.實戰(zhàn)案例
業(yè)務(wù)背景: 在電商項目的售后業(yè)務(wù)中携取,當(dāng)客服接收到用戶的售后申請時雷滋,需要進(jìn)行一系列操作晤斩,包括查詢訂單信息澳泵、查詢 ERP 中的商品信息兔辅、查詢用戶信息维苔,以及創(chuàng)建售后工單介时。
public CompletableFuture<Void> processAfterSalesRequest(String orderId, String customerId) {
CompletableFuture<Order> orderFuture = CompletableFuture.supplyAsync(() -> getOrderInfo(orderId));
CompletableFuture<Inventory> inventoryFuture = CompletableFuture.supplyAsync(() -> getInventoryInfo(orderId));
CompletableFuture<User> userFuture = CompletableFuture.supplyAsync(() -> getUserInfo(customerId));
return CompletableFuture.allOf(orderFuture, inventoryFuture, userFuture)
.thenApplyAsync(ignored -> {
Order order = orderFuture.join();
Inventory inventory = inventoryFuture.join();
User user = userFuture.join();
// 創(chuàng)建售后工單
createAfterSalesTicket(order, inventory, user);
return null;
});
}
private Order getOrderInfo(String orderId) {
// 查詢訂單信息的邏輯
// ...
return order;
}
private Inventory getInventoryInfo(String orderId) {
// 查詢ERP中商品信息的邏輯
// ...
return inventory;
}
private User getUserInfo(String customerId) {
// 查詢用戶信息的邏輯
// ...
return user;
}
private void createAfterSalesTicket(Order order, Inventory inventory, User user) {
// 創(chuàng)建售后工單的邏輯
// ...
}
四、線程池
經(jīng)常創(chuàng)建和銷毀羹蚣、使用量特別大的資源顽素,比如并發(fā)情況下的線程胁出,對性能影響很大全蝶。
思路:提前創(chuàng)建好多個線程抑淫,放入線程池中始苇,使用時直接獲取催式,使用完放回池中荣月。
可以避免頻繁創(chuàng)建銷毀哺窄、實現(xiàn)重復(fù)利用堂氯。類似生活中的公共交通工具咽白。
好處:
- 提高響應(yīng)速度(減少了創(chuàng)建新線程的時間)
- 降低資源消耗(重復(fù)利用線程池中線程晶框,不需要每次都創(chuàng)建)
- 便于線程管理
- corePoolSize:核心池的大小
- maximumPoolSize:最大線程數(shù)
- keepAliveTime:線程沒有任務(wù)時最多保持多長時間后會終止
JDK 5.0起提供了線程池相關(guān)API:ExecutorService 和 Executors
ExecutorService:真正的線程池接口授段。常見子類ThreadPoolExecutor
- void execute(Runnable command) :執(zhí)行任務(wù)/命令侵贵,沒有返回值窍育,一般用來執(zhí)行RunnableFuture
- submit(Callable task):執(zhí)行任務(wù)表锻,有返回值瞬逊,一般又來執(zhí)行
- Callablevoid shutdown() :關(guān)閉連接池
Executors:工具類确镊、線程池的工廠類骚腥,用于創(chuàng)建并返回不同類型的線程池
public class MyThreadPool implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
public static void main(String[] args) {
// 線程池
ExecutorService pool = Executors.newFixedThreadPool(10);
ThreadPoolExecutor executor = (ThreadPoolExecutor) pool;
/*
* 可以做一些操作:
* corePoolSize:核心池的大小
* maximumPoolSize:最大線程數(shù)
* keepAliveTime:線程沒任務(wù)時最多保持多長時間后會終止
*/
executor.setCorePoolSize(5);
// 開啟線程
executor.execute(new MyThreadPool());
executor.execute(new MyThreadPool());
executor.execute(new MyThreadPool());
executor.execute(new MyThreadPool());
}
}