本文章实现了多线程中套用多线程的方式来处理大数据刚并发的情况
准备工作:自定义线程池命名规则,可以不需要
public class NamedThreadFactory implements ThreadFactory {
private final static Logger logger = LoggerFactory.getLogger(NamedThreadFactory.class);
private static AtomicInteger tag = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("thread-call-runner-%d"+ tag.getAndIncrement());
logger.info("thread name: {}", thread.getName());
return thread;
}
准备工作:创建线程池
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Component
public class ExecutorUtil {
@Value("${executor.threadcnt}")
private Integer threadCnt;
private ExecutorService executorService;
@PostConstruct
public void init(){
NamedThreadFactory namedThreadFactory = new NamedThreadFactory();
// 自定义线程池线程个数
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,new SynchronousQueue<>(),namedThreadFactory );
// 不设置线程池个数,线程执行完后会自己回收线程
executorService = Executors.newCachedThreadPool();
}
@PreDestroy
public void shutdown(){
tearDown(executorService);
}
public ExecutorService getExecutorService() {
return executorService;
}
public static ExecutorService getExecutorService(int threadCnt) {
return Executors.newFixedThreadPool(threadCnt);