一、基本概念
1.什么是进程?
image.png电脑中会有很多单独运行的程序,每个程序有一个独立的进程,而进程之间是相互独立存在的。
例如图中的微信、Chrome、idea等等。
2.什么是线程?
进程想要执行任务就需要依赖线程。
进程中的最小执行单位就是线程,并且一个进程中至少有一个线程。
补充:Java中有默认有几个线程?两个:main、gc
那什么又是多线程呢?
提到多线程这里要说两个概念,就是串行和并行,搞清楚这个,我们才能更好地理解多线程。
串行:
并行:
二、线程的创建
Java 提供了三种创建线程的方法:
// 通过继承 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
// 或使用匿名内部类
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();
}
}
// 通过实现 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 创建线程
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);
//传入线程执行目标,实例化线程对象
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 中引入的一个类
它实现了CompletionStage接口,提供了一组丰富的方法来处理异步操作和多个任务的结果。
它支持链式操作,可以方便地处理任务的依赖关系和结果转换。
相比于传统的Future接口,CompletableFuture更加灵活和强大。
CompletableFuture的使用具有以下优势和特点:
- 异步执行:CompletableFuture允许任务在后台线程中异步执行,不会阻塞主线程,提高了应用程序的响应性和性能。
- 链式操作:通过CompletableFuture提供的方法,可以方便地对任务进行链式操作,构建复杂的任务依赖关系,实现高效的任务调度和执行。
- 异常处理:CompletableFuture提供了丰富的异常处理方法,可以处理任务执行过程中可能发生的异常,并实现灵活的错误处理和回退机制。
- 多任务组合:CompletableFuture支持多个任务的并发执行和结果组合。可以轻松地实现多任务并发处理的场景,提高应用程序的效率和并发性。
2. 具体使用网上有很多文档
个人觉得这种方式最优雅,也是我最常使用的。
public class TestCompletableFuture {
public static void main(String[] args) {
CompletableFuture.runAsync(() -> System.out.println(Thread.currentThread().getName() + " 1")).join();
}
}
3.实战案例
业务背景: 在电商项目的售后业务中,当客服接收到用户的售后申请时,需要进行一系列操作,包括查询订单信息、查询 ERP 中的商品信息、查询用户信息,以及创建售后工单。
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();
// 创建售后工单
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) {
// 创建售后工单的逻辑
// ...
}
四、线程池
经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。
可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
好处:
- 提高响应速度(减少了创建新线程的时间)
- 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
- 便于线程管理
- corePoolSize:核心池的大小
- maximumPoolSize:最大线程数
- keepAliveTime:线程没有任务时最多保持多长时间后会终止
JDK 5.0起提供了线程池相关API:ExecutorService 和 Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
- void execute(Runnable command) :执行任务/命令,没有返回值,一般用来执行RunnableFuture
- submit(Callable task):执行任务,有返回值,一般又来执行
- Callablevoid shutdown() :关闭连接池
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
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:最大线程数
* keepAliveTime:线程没任务时最多保持多长时间后会终止
*/
executor.setCorePoolSize(5);
// 开启线程
executor.execute(new MyThreadPool());
executor.execute(new MyThreadPool());
executor.execute(new MyThreadPool());
executor.execute(new MyThreadPool());
}
}
网友评论