ExecutorService by a thread and returns the value of existing Callable Mika

Need to open the main thread concurrent execution of multiple threads in a task, and then returns the results collected by each thread of execution and the final results are summarized, then you need Callable interface.

Now Mika method: to create and implement a class Callable interface, logic call specific calculation process, and returns the results.

Specific call the procedure: create a thread pool, a Future List and Callable thread Mika patients receiving the returned results for the submitted task using a thread pool and the results after the thread execution stored in the Future, the traversal Future List at the end of the thread execution the Future object, call the get method on the object that is the thread can get to the data Callable task returns and summary results.

Example:

import java.util.concurrent.Callable;

/**
 * ① 通过Callable接口创建MyCallable线程
 */
public class MyCallable implements Callable<String> {

    private String name;

    /**
     * 通过构造器为线程传递参数,以定义线程的名称
     * @param name
     */
    public MyCallable(String name){
        this.name = name;
    }

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public String call() throws Exception {
        return name;
    }
}
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;

/**
 * 测试MyCallable
 */
public class TestMyCallable {
    public void test() {

        // ② 创建一个固定大小为7的线程
        ExecutorService pool = Executors.newFixedThreadPool(6);
        // ③ 创建多个有返回值的任务列表list
        List<Future> taskList = new ArrayList<Future>();

        for(int i = 0; i < 6; i++ ){
            // ④创建一个有返回值的线程実例
            Callable c = new MyCallable(i + " ");
            // ⑤提交线程,获取Future对象并将其保存到Future List 中
            Future future = pool.submit(c);
            System.out.println("Submit a callable thread: "+i);
            taskList.add(future);
        }

        // ⑥ 关闭线程池,等待线程执行结束
        pool.shutdown();
        // ⑦ 遍历所有线程的运行结果
        taskList.forEach(future  -> {
            //从Future对象中获取任务返回值,并将结果输出于控制台。
            System.out.println("Get the resullt from callable thread: " +
                    futureGet(future)
            );
        });

    }
    private <E extends Exception> String futureGet(Future future) throws E{
        try {
            return future.get().toString();
        } catch (Exception e) {
            throw (E) e;
        }
    }
}

 

Published 28 original articles · won praise 3 · Views 5296

Guess you like

Origin blog.csdn.net/u012632105/article/details/104651141