配置线程池
public static ThreadPoolExecutor executor = new ThreadPoolExecutor(100, 200,
300 , TimeUnit.SECONDS, new LinkedBlockingDeque<>(10000),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
编写多线程方法
@CrossOrigin
@ApiOperation("测试")
@PostMapping(value="test")
public void Test() throws ExecutionException, InterruptedException {
int count = 100;
long startTime=System.currentTimeMillis();
List<CompletableFuture> completableFutures=new ArrayList<>();
for(int j=0;j<count;j++){
int finalJ = j;
CompletableFuture<Void> future=CompletableFuture.runAsync(()->{
System.out.println("当前线程名是:"+Thread.currentThread().getName()+" "+finalJ);
try {
---此处添加逻辑计算代码段----
method();
---此处添加逻辑计算代码段----
} catch (InterruptedException e) {
e.printStackTrace();
}
},executor);
completableFutures.add(future);
}
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).get();
long endTime=System.currentTimeMillis();
System.out.println("总耗时:"+(endTime-startTime));
}
示例对比代码
public static ThreadPoolExecutor executor = new ThreadPoolExecutor(100, 200,
300 , TimeUnit.SECONDS, new LinkedBlockingDeque<>(10000),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
@ApiOperation("测试")
@PostMapping(value="test")
public void Test() throws ExecutionException, InterruptedException {
int count = 100;
long startTime=System.currentTimeMillis();
List<CompletableFuture> completableFutures=new ArrayList<>();
for(int j=0;j<count;j++){
int finalJ = j;
CompletableFuture<Void> future=CompletableFuture.runAsync(()->{
System.out.println("当前线程名是:"+Thread.currentThread().getName()+" "+finalJ);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
},executor);
completableFutures.add(future);
}
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).get();
long endTime=System.currentTimeMillis();
System.out.println("总耗时:"+(endTime-startTime));
}
@CrossOrigin
@ApiOperation("测试")
@PostMapping(value="test1")
public void Test1() throws ExecutionException, InterruptedException {
int count = 100;
long startTime=System.currentTimeMillis();
for(int j=0;j<count;j++){
System.out.println("当前线程名是:"+Thread.currentThread().getName()+" "+j);
TimeUnit.SECONDS.sleep(1);
}
long endTime=System.currentTimeMillis();
System.out.println("总耗时:"+(endTime-startTime));
}
对比结果 test总耗时:1032毫秒,test1总耗时:101021毫秒