CompletionService测试demo、异步任务、多线程

使用场景:将耗时任务同时执行,比如通过rpc从多接口获取数据组装的时候,可以同时调多个接口。

demo

package a;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CompletionServiceTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = CompletionServiceTest.exec;
        CompletionService completionService = new ExecutorCompletionService(executorService);
        List<Future> taskList = new ArrayList<Future>();
        CompletionServiceTest completionServiceTest=new CompletionServiceTest();
        Datatest datatest=new Datatest();
        taskList.add(completionService.submit(() -> {
            datatest.a=completionServiceTest.add1();
            return true;
        }));
        taskList.add(completionService.submit(() -> {
            datatest.b=completionServiceTest.add2();
            return true;
        }));
        taskList.add(completionService.submit(() -> {
            datatest.c=completionServiceTest.add3();
            return true;
        }));
        taskList.add(completionService.submit(() -> {
            datatest.d=completionServiceTest.add4();
            return true;
        }));
        Long time1=System.currentTimeMillis();
        for (int i = 0, size = taskList.size(); i < size; i++) {
            try {
                completionService.take().get();
            }  catch (ExecutionException e) {
                throw new RuntimeException("异步查询异常");
            }
        }
        System.out.println(datatest);
        System.out.println("异步执行时间:"+(System.currentTimeMillis()-time1));
        time1=System.currentTimeMillis();
        completionServiceTest.add1();
        completionServiceTest.add2();
        completionServiceTest.add3();
        completionServiceTest.add4();
        System.out.println("主线程执行时间:"+(System.currentTimeMillis()-time1));

    }


    /**
     * 模拟耗时的一些操作
     */
    public Integer add1() throws InterruptedException {
        Thread.sleep(3000);
        System.out.println("add1"+Thread.currentThread().getName());
        return 1;
    }
    /**
     * 模拟耗时的一些操作
     */
    public Integer add2() throws InterruptedException {
        Thread.sleep(2000);
        System.out.println("add2"+Thread.currentThread().getName());
        return 2;
    }
    /**
     * 模拟耗时的一些操作
     */
    public Integer add3() throws InterruptedException {
        Thread.sleep(800);
        System.out.println("add3"+Thread.currentThread().getName());
        return 3;
    }
    /**
     * 模拟耗时的一些操作
     */
    public Integer add4() throws InterruptedException {
        Thread.sleep(600);
        System.out.println("add4"+Thread.currentThread().getName());
        return 4;
    }
    /**
     * 数据实体
     */
    static class Datatest{
        Integer a;
        Integer b;
        Integer c;
        Integer d;
        @Override
        public String toString() {
            return "Datatest{" +
                    "a=" + a +
                    ", b=" + b +
                    ", c=" + c +
                    ", d=" + d +
                    '}';
        }
    }

    public static final ExecutorService exec =  new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 50, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(),
            new ThreadFactory() {
                private final String threadPoolPrefix = "ThreadPool-Thread-";
                public AtomicInteger counter = new AtomicInteger(0);
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName(threadPoolPrefix+counter.incrementAndGet());
                    //设定为守护线程
                    if (t.isDaemon()){
                        t.setDaemon(false);
                    }
                    //设定线程优先级
                    if (t.getPriority() != Thread.NORM_PRIORITY){
                        t.setPriority(Thread.NORM_PRIORITY);
                    }
                    return t;
                }
            });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值