多线程Callable使用

参考博文:
1.https://www.cnblogs.com/dolphin0520/p/3932921.html
2.https://www.cnblogs.com/dolphin0520/p/3949310.html
3.https://www.cnblogs.com/zincredible/p/10984459.html
4.https://www.cnblogs.com/shoshana-kong/p/9071602.html

1.创建类实现Callable接口

public class MyCallable implements Callable {

    private String data;

    public MyCallable(String data) {
        this.data = data;
    }

    @Override
    public String call() throws Exception {
        System.out.println("当前线程名称:"+Thread.currentThread().getName());
        System.out.println("当前数据名称:"+data);
        try {
            System.out.println("开始处理:"+data);
            Thread.sleep(1000);
            System.out.println("处理结束:"+data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return data;
    }
}

2.callable的使用

public class CallableTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List datas = Lists.newArrayList();
        datas.add("data1");
        datas.add("data2");
        datas.add("data3");
        long start = System.currentTimeMillis();

        //模拟处理3条数据
        for(int i=0; i<3; i++){
            MyCallable myCallable = new MyCallable(datas.get(i));
            FutureTask futureTask = new FutureTask(myCallable);
            new Thread(futureTask).start();

        }
        System.out.println("处理数据消耗:"+(System.currentTimeMillis()-start));
    }

}

3.callable在线程池有返回的使用

public class ThreadPoolTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        List datas = Lists.newArrayList();
        datas.add("data1");
        datas.add("data2");
        datas.add("data3");
        long start = System.currentTimeMillis();

        ExecutorService executorService = Executors.newCachedThreadPool();
        List> futureTasks = new ArrayList<>();

        //模拟处理3条数据
        for(int i=0; i<3; i++){
            MyCallable myCallable = new MyCallable(datas.get(i));
            FutureTask futureTask = new FutureTask(myCallable);
            futureTasks.add(futureTask);
            //无需返回
//            executorService.execute(futureTask);
            //需要返回
            executorService.submit(futureTask);
        }
        executorService.shutdown();
        //返回结果
        for(int i=0; i

你可能感兴趣的:(多线程Callable使用)