线程回调-实现Callable<T>接口

线程回调-实现Callable<T>接口

线程回调顾名思义就是获取一个线程中返回的结果,通过实现接口Callable<T>来实现。

例子:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
class Mythread implements Callable<String>{
      int i = 0;     
      public Mythread(int i) {
            this.i = i;
            }
      @Override
      public String call() throws Exception {
            // TODO Auto-generated method stub
            System.out.println("线程启动---" + Thread.currentThread().getName()
                        + new Date());
            try {
                  Thread.sleep(i);
                  System.out.println("休眠了"+i+"毫秒 线程结束---" + Thread.currentThread().getName()
                              + new Date());
            } catch (Exception e) {
                  // TODO: handle exception
            }
             return "sucess"+i;
      };    
}
public class 线程池执行完毕后返回结果 {
      public static ExecutorService cachedThreadPool = Executors
                  .newFixedThreadPool(20);
      public static void main(String[] args) {
            ArrayList<Mythread> list = new ArrayList<Mythread>();
            for (int i = 0; i < 7; i++) {
                  list.add(new Mythread(i*1000));
            }
            try {
                  List<Future<String>> invokeAll = cachedThreadPool.invokeAll(list);
                  System.out.println("--------------------------------------");
                  for (Future<String> fu : invokeAll) {
                  System.out.println(fu.get());
                  }
            } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (ExecutionException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }      
      }
}

 控制台打印输出:

通过控制台打印的结果我们能发现:

所谓的线程回调就是获取线程中返回的结果。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

栗子~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值