代码示例
在配置文件中获取线程池的配置参数
ThreadPoolConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class ThreadPoolConfig {
@Bean
public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties pool){
return new ThreadPoolExecutor(pool.getCoreSize(),pool.getMaxSize(),pool.getKeepAliveTime(), TimeUnit.SECONDS,new LinkedBlockingDeque<>(100000),
Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
}
}
ThreadPoolConfigProperties.java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "canbot.thread")
@Component
@Data
public class ThreadPoolConfigProperties {
private Integer coreSize;
private Integer maxSize;
private Integer keepAliveTime;
}
application.properties文件:
canbot.thread.core-size=20
canbot.thread.max-size=200
canbot.thread.keep-alive-time=10
业务代码演示
//多任务组合 ,测试执行三个任务所消耗的时间,最后总的时间应该是三个任务中耗时最长的那一个任务
@Test
public void testCompletableFuture5() throws Exception{
long startTime=System.currentTimeMillis();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的的图片信息" + Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello.jpg";
}, executorService);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的属性" + Thread.currentThread().getId());
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "黑色+256G";
}, executorService);
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
System.out.println("查询商品的介绍" + Thread.currentThread().getId());
try {
Thread.sleep(1200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "华为";
}, executorService);
future1.get();
future2.get();
future3.get();
long time=System.currentTimeMillis()-startTime;
System.out.println("任务消耗的总时间为"+time);
}
//测试得到任务消耗的总时间为1503,说明任务是异步进行的
其中 future1.get(); future2.get(); future3.get();代码太过于冗余,可以使用下面两句话进行代替
1、CompletableFuture allOf = CompletableFuture.allOf(future1, future2, future3);
2、allOf.join();
考虑到
总结
使用线程池处理任务可以提高系统的吞吐量,提升系统的性能