多线程之实现Callable

本文探讨了在Java中利用多线程并发处理大数据的方法,包括创建线程池、从MQ消费数据、重写Callable的call方法以及多线程中的具体实现细节。
摘要由CSDN通过智能技术生成

本文章实现了多线程中套用多线程的方式来处理大数据刚并发的情况 

准备工作:自定义线程池命名规则,可以不需要 

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);
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值