java Callable接口线程返回参数


package com.qd.thread.callable;

import java.util.concurrent.Callable;

/**
 * Created by chenlongbo on 2017/4/24.
 */
public class TaskWithResult implements Callable<String>{
    private int id;

    public TaskWithResult(int id){
        this.id = id;
    }

    public String call() throws Exception {
        return " result of TaskWithResult : "+id;
    }
}
package com.qd.thread.callable;

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

/**
 * Created by chenlongbo on 2017/4/24.
 */
public class CallableDemo {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> futures = new ArrayList<Future<String>>();
        for (int i = 0; i < 10; i++) {
            futures.add(exec.submit(new TaskWithResult(i)));
        }

        for(Future<String> fs:futures){
            try {
                System.out.println(fs.get());
            } catch (InterruptedException e) {
                System.out.println(e);
                e.printStackTrace();
                return;
            } catch (ExecutionException e) {
                System.out.println(e);
                e.printStackTrace();
            }finally {
                exec.shutdown();
            }
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM