java动态线程池LinkedBlockingQueue和SynchronousQueue比较

本文通过实现一个自定义的可调用任务MyCallable,并使用不同类型的队列配置线程池,对比了SynchronousQueue与LinkedBlockingQueue在处理大量任务时的性能差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.concurrent.Callable;

public class MyCallable implements Callable<String> {
    private String name; 
    public MyCallable(String name){ 
        this.name=name;
    }
    @Override
    public String call() throws Exception {
        System.out.println("Thread begin "+name);
        Thread.sleep(1000);
        return name;
    }
}
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class DynamicThreadPool {
    public static void main(String[] args) {
        /*ThreadPoolExecutor taskExecutor  = new ThreadPoolExecutor(
                1,100,5, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(100), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());*/
        ThreadPoolExecutor taskExecutor  = new ThreadPoolExecutor(
                1,100,5, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
        long a=System.nanoTime();
         CompletionService<String> cs = new ExecutorCompletionService<>(taskExecutor);
            for (int i = 0; i < 100; i++) {
                cs.submit(new MyCallable("Thread "+i));
            }
            for (int i = 0; i < 100; i++){
                 try {
                    System.out.println(cs.take().get());
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }  
            }
        System.out.println(System.nanoTime()-a);
    }
                      任务数(1任务耗时1秒)       用时(纳秒)       队列长度
SynchronousQueue            100                 1010688455        
LinkedBlockingQueue         100                   太长             100
SynchronousQueue            1000                12041095086       
LinkedBlockingQueue         1000                10073587003        100
SynchronousQueue            10000               129230529016      
LinkedBlockingQueue         10000               100583218224       100

 

转载于:https://www.cnblogs.com/tonggc1668/p/7280400.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值