Java中线程池使用样例

一般使用样例

public class ThreadPoolUtils {



    public static ThreadPoolExecutor getThreadPool(String name, BlockingQueue<Runnable> queue, int numThreads) {
        String threadGroupName = "learn.demo-" + name;
        ThreadGroup threadGroup = new ThreadGroup(threadGroupName);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(numThreads, numThreads * 2
                , 30, TimeUnit.SECONDS, queue,
                new SyncRuleThreadFactory(name, threadGroup, Thread.NORM_PRIORITY),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        pool.prestartAllCoreThreads();
        return pool;
    }

    private static class SyncRuleThreadFactory implements ThreadFactory {
        private final String prefix;
        private final ThreadGroup threadGroup;
        private final int threadPriority;
        private int currThreadCount;

        public SyncRuleThreadFactory(String prefix, ThreadGroup threadGroup, int threadPriority) {
            this.prefix = prefix;
            this.threadGroup = threadGroup;
            this.threadPriority = threadPriority;
        }

        @Override
        public Thread newThread(Runnable r) {
            String name = prefix + "-" + currThreadCount;
            currThreadCount++;
            Thread thread = new Thread(threadGroup, r, name);
            // 捕获运行时异常
            thread.setUncaughtExceptionHandler((t, e) -> {
                System.out.println("线程" + t.getName() + " 运行出错:" + e);
            });
            thread.setPriority(threadPriority);
            return thread;
        }
    }
}
public class ThreadPoolDemo {
    public static void main(String[] args) {
        BlockingQueue<Runnable> syncRuleQueue = new LinkedBlockingQueue<>();

        ThreadPoolExecutor threadPool = ThreadPoolUtils.getThreadPool("send sms", syncRuleQueue, 10);
        // 模拟发送多条短信
        for (int i = 0; i < 200; i++) {
            int messageId = i + 1;
            threadPool.submit(() -> sendSms("Message " + messageId));
        }

        // 关闭线程池
        threadPool.shutdown();
    }

    // 模拟发送短信的方法
    private static void sendSms(String message) {
        try {
            System.out.println("Sending SMS: " + message + "this thread is " + Thread.currentThread().getName());
            // 模拟网络延迟
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Failed to send SMS: " + message);
        }
    }
}

spring注解使用样例

@Configuration
@EnableAsync
public class ThreadPoolConfig {
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    private static final int COUR_SIZE = CPU_COUNT * 2;

    private static final int MAX_COUR_SIZE = CPU_COUNT * 4;

    private static final String THREAD_NAME = "sendSms";

    private static final BlockingQueue<Runnable> SYNC_RULE_QUEUE = new LinkedBlockingQueue<>();

    @Bean(name = "sendSmsExcelExecutor")
    public ThreadPoolExecutor getThreadPool() {
        String threadGroupName = "learn.demo-" + THREAD_NAME;
        ThreadGroup threadGroup = new ThreadGroup(threadGroupName);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(COUR_SIZE, MAX_COUR_SIZE
                , 30, TimeUnit.SECONDS, SYNC_RULE_QUEUE,
                new SyncRuleThreadFactory(THREAD_NAME, threadGroup, Thread.NORM_PRIORITY),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        pool.prestartAllCoreThreads();
        return pool;
    }

    private static class SyncRuleThreadFactory implements ThreadFactory {
        private final String prefix;
        private final ThreadGroup threadGroup;
        private final int threadPriority;
        private int currThreadCount;

        SyncRuleThreadFactory(String prefix, ThreadGroup threadGroup, int threadPriority) {
            this.prefix = prefix;
            this.threadGroup = threadGroup;
            this.threadPriority = threadPriority;
        }

        @Override
        public Thread newThread(Runnable r) {
            String name = prefix + "-" + currThreadCount;
            currThreadCount++;
            Thread thread = new Thread(threadGroup, r, name);
            // 捕获运行时异常
            thread.setUncaughtExceptionHandler((t, e) -> System.out.println("线程" + t.getName() + " 运行出错:" + e));
            thread.setPriority(threadPriority);
            return thread;
        }
    }
}
@Service
public class SedMessageServiceImpl implements SedMessageService{

    @Override
    @Async("sendSmsExcelExecutor")
    public void exportDataToExcel(String message) {
        try {
            System.out.println("Sending SMS: " + message + "this thread is " + Thread.currentThread().getName());
            // 模拟网络延迟
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Failed to send SMS: " + message);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值