ExecutorService vs ComletionService vs ScheduledExecutorServce

ExcutorService

1.在多个项目中使用到了这个类,对这个类的方法,大概有所了解,现在写点体会。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ThreadDemo {

    public final ExecutorService threadPool = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        new ThreadDemo().solveCallableList();
    }

    public void solveCallableList() {
        try {
            int sum = 0;
            List<Callable<Integer>> callableList = new ArrayList<Callable<Integer>>();
            callableList.add(new TaskCallable(1));
            callableList.add(new TaskCallable(2));
            callableList.add(new TaskCallable(3));
            List<Future<Integer>> list = threadPool.invokeAll(callableList, 2000L, TimeUnit.MILLISECONDS);
            if (list != null && list.size() > 0) {
                for (Future<Integer> future : list) {
                    int result = future.get();
                    sum += result;
                }
            }
            System.out.println("sum = " + sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class TaskCallable implements Callable<Integer> {
        private int options;

        TaskCallable(int options) {
            this.options = options;
        }

        @Override
        public Integer call() throws Exception {
            try {
                switch (options) {
                case 1:
                    return Integer.valueOf(2 / 0);
                case 2:
                    return Integer.valueOf(2 + 1);
                case 3:
                    return Integer.valueOf(2 - 1);
                default:
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

threadPool添加三个计算任务,然后分别计算这三个任务的和,执行结果如下:

java.lang.ArithmeticException: / by zero
    at cn.kuwo.threadDemo.ThreadDemo$TaskCallable.call(ThreadDemo.java:51)
    at cn.kuwo.threadDemo.ThreadDemo$TaskCallable.call(ThreadDemo.java:1)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
    at cn.kuwo.threadDemo.ThreadDemo.solveCallableList(ThreadDemo.java:29)
    at cn.kuwo.threadDemo.ThreadDemo.main(ThreadDemo.java:16)

用到了threadPool.invokeAll方法,执行全部的方法,发现只要有一个计算任务,有异常,那么就会影响整体的任务计算。这个类中还有许多其他有意思的方法,请查看这里

ComletionService

1.针对上述情况,其实有时候我们需要在执行多个任务的时候,需要得到其中顺利执行完成的任务,对于那些没有执行成功我们有时候并不怎么关心(或者期待下次执行的时候获得正确的结果)

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadDemo1 {
    public final ExecutorService threadPool = Executors.newCachedThreadPool();
    public final CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool);

    public static void main(String[] args) {
        new ThreadDemo1().solveCallableList();
    }

    public void solveCallableList() {
        try {
            int sum = 0;
            completionService.submit(new TaskCallable(1));
            completionService.submit(new TaskCallable(2));
            completionService.submit(new TaskCallable(3));
            for (int i = 0; i < 3; i++) {
                int result = completionService.take().get();
                sum += result;
            }
            System.out.println("sum = " + sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class TaskCallable implements Callable<Integer> {
        private int options;

        TaskCallable(int options) {
            this.options = options;
        }

        @Override
        public Integer call() throws Exception {
            try {
                switch (options) {
                case 1:
                    return Integer.valueOf(2 / 0);
                case 2:
                    return Integer.valueOf(2 + 1);
                case 3:
                    return Integer.valueOf(2 - 1);
                default:
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        }
    }
}

在上述的代码中,其中我们能够看到只需要在子计算任务的时候捕获异常,那么就不会影响整体任务的执行结果,结果:

java.lang.ArithmeticException: / by zero
    at cn.kuwo.threadDemo.ThreadDemo1$TaskCallable.call(ThreadDemo1.java:45)
    at cn.kuwo.threadDemo.ThreadDemo1$TaskCallable.call(ThreadDemo1.java:1)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
sum = 4

ScheduledExecutorServce

1.这个类在需要执行简单的定时任务(或加载配置文件到内存中)的时候,可以用这个,下面是个简单的demo

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadDemo2 {
    public static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    static{
        scheduledExecutorService.scheduleAtFixedRate(new Runnable(){
            @Override
            public void run() {
                System.out.println(new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(new Date())+ " load properties success");
            }

        }, 0, 2, TimeUnit.SECONDS);

    }
    public static void main(String[] args){
        System.out.println("dsf");
    }
}

对于简单的配置文件信息比较好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值