欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程之callable接收返回值

程序员文章站 2022-06-07 16:05:05
...

实现一个线程有三种方案,分别为继承Thread、实现Runnbale和实现Callable,Callable相对Runnable而言,可以实现对结果的接受,现就callable接受返回值并处理进行简单实践,
实现过程如下:

  1. 设计一个线程操作类CallableTest,实现Callable接口。
  2. 初始化一个线程池service。
  3. 实例化CallableTest。
  4. 初始化一个list。
  5. 使用线程池调度callabletest任务,并将返回值存储到list中。
  6. list遍历。

CallableTest

package com.callable;

import java.util.Date;
import java.util.concurrent.Callable;

/**
 * @author 席鹏
 * @date 2021-07-17 14:19
 * @description:
 */
public class CallableTest implements Callable {
    @Override
    public Object call() throws Exception {
        Thread.sleep(10);
        System.out.println("当前线程:"+Thread.currentThread().getName());
        return new Date();
    }
}

测试类

package com.callable;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author 席鹏
 * @date 2021-07-17 14:20
 * @description:
 */
public class TestRun {
    @Test
    public void testRun() throws ExecutionException, InterruptedException {
        CallableTest callableTest = new CallableTest();
        ExecutorService service = Executors.newFixedThreadPool(3);
        ArrayList<Future<Date>> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(service.submit(callableTest));
        }

        for (Future<Date> dateFuture : list) {
            System.out.println(dateFuture.get());
        }

    }
}

运行结果

当前线程:pool-1-thread-3
当前线程:pool-1-thread-1
当前线程:pool-1-thread-2
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
当前线程:pool-1-thread-1
当前线程:pool-1-thread-3
当前线程:pool-1-thread-2
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
当前线程:pool-1-thread-2
当前线程:pool-1-thread-3
当前线程:pool-1-thread-1
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
当前线程:pool-1-thread-3
当前线程:pool-1-thread-2
当前线程:pool-1-thread-1
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
当前线程:pool-1-thread-2
当前线程:pool-1-thread-3
当前线程:pool-1-thread-1
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
当前线程:pool-1-thread-2
当前线程:pool-1-thread-1
当前线程:pool-1-thread-3
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
当前线程:pool-1-thread-2
当前线程:pool-1-thread-1
Sat Jul 17 14:44:38 CST 2021
Sat Jul 17 14:44:38 CST 2021
Process finished with exit code 0

相关标签: 个人java学习笔记