package com.ctc.north.local.service.component.credit;
import com.ctc.north.local.api.model.uncomplex.response.VentureStopResponse;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @author zhuxx
* @desc 线程池测试
**/
public class ExcutorsTest {
public static void main(String[] args) {
//待处理的数据集合List
List<UserVo> userList = getUservoList();
LinkedBlockingDeque blockingDeque = new LinkedBlockingDeque<Callable>(userList.size());
//submit返回Future结果
List<Future> futureList = new ArrayList<Future>();
//CountDownLatch是一个同步计数器,能够保证在其他线程完成某一个业务操作前,当前线程一直处于等待/阻塞状态。
//具体来说,这个计数器将会从给定的某一个数值count开始,通过countDown()方法的调用进行倒数。
//当执行某一次countDown()操作后,计数器的count数值等于0,所有调用了await()方法的线程,就解除等待/阻塞状态继续执行
CountDownLatch latch = new CountDownLatch(userList.size());
//ThreadFactory就是一个线程工厂负责生产线程的
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("venture-stop-%d").build();
//创建线程池
ExecutorService cachedThreadPool = new ThreadPoolExecutor(3,
6,
0,
TimeUnit.SECONDS,
blockingDeque, threadFactory);
//ExecutorCompletionService将BlockingQueue和Executor封装起来,然后使用ExecutorCompletionService.submit()方法提交任务。
//<String>数据类型与Callable返回的数据类型一致;
CompletionService<String> cs = new ExecutorCompletionService<String>(cachedThreadPool);
userList.stream().forEach(userVo -> {
//处理任务
Callable<String> callable = () -> {
latch.countDown();
System.out.println("线程名称:"+Thread.currentThread().getName());
System.out.println("线程返回值:"+userVo.id+"-1");
return userVo.id+"-1";
};
futureList.add(cs.submit(callable));
});
try {
//所有子线程执行完毕(计数器的count数值等于0),可以继续执行
latch.await();
System.out.println("执行结果:");
futureList.stream().forEach(futrue ->{
try {
//获取线程执行结果
System.out.println(futrue.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("==============================================");
}
public static List<UserVo> getUservoList(){
List<UserVo> userList = new ArrayList<UserVo>();
for(int i=0;i<6;i++){
UserVo userVo = new UserVo();
userVo.id=i+"00";
userVo.name="AA"+i;
userVo.age="2"+i;
userList.add(userVo);
}
return userList;
}
}
class UserVo{
public String id;
public String name;
public String age;
}
执行结果如下:
注意:
如果需要通过线程池执行任务,无需关注返回结果,即如下操作:
1、去掉CountDownLatch latch = new CountDownLatch(userList.size());
2、去掉latch.countDown();
3、去掉latch.await();