Callable 的使用

通过实现callable的call方法可以完成线程的操作,并且返回一个需要的值

package test1;

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

public class TaskWithResult implements Callable<String> {
    
    // 实现call方法,在方法中输出两句话
    public String call() throws Exception {
        //Thread.sleep(time);
        System.out.println(Thread.currentThread().getName() + "run...");
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "test...");
        // 返回一个字符串
        return Thread.currentThread().getName() + " has executed";
    }
    
    
    
    
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 用Executors来管理线程
        ExecutorService exec = Executors.newCachedThreadPool();
        // 用Future来接受返回值
        List<Future<String>> results = new ArrayList<Future<String>>();
        for(int i=0; i<=10; i++){
            // 将返回值放入Future<String>类型的List中去
            results.add(exec.submit(new TaskWithResult()));
        }
        // 得到返回值
        //System.out.println(results.get(0).get());
        exec.shutdown();
    }
}

输出结果

pool-1-thread-1run...
pool-1-thread-2run...
pool-1-thread-3run...
pool-1-thread-4run...
pool-1-thread-5run...
pool-1-thread-7run...
pool-1-thread-8run...
pool-1-thread-9run...
pool-1-thread-11run...
pool-1-thread-6run...
pool-1-thread-10run...
pool-1-thread-2test...
pool-1-thread-1test...
pool-1-thread-4test...
pool-1-thread-3test...
pool-1-thread-9test...
pool-1-thread-8test...
pool-1-thread-7test...
pool-1-thread-5test...
pool-1-thread-10test...
pool-1-thread-6test...
pool-1-thread-11test...

看出来程序不是顺序运行的,而是将每一个线程分时运行。

 

可以通过Future的get()来得到返回值

pool-1-thread-1test...
pool-1-thread-1 has executed
pool-1-thread-3test...
pool

 

 

 

转载于:https://www.cnblogs.com/xinyuyu/p/3706508.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值