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

创建线程之三:实现Callable接口

程序员文章站 2022-06-29 20:33:37
通过Callable和Future创建线程 i. 创建Callable接口的实现类,并实现call方法,该call方法将作为线程执行体,并且有返回值,可以抛出异常。 ii. 创建Callable实现类的实例,使用FutureTask类包装Callable对象,该FuturedTask对象封装了Cal ......

通过callable和future创建线程

  i. 创建callable接口的实现类,并实现call方法,该call方法将作为线程执行体,并且有返回值,可以抛出异常。

  ii. 创建callable实现类的实例,使用futuretask类包装callable对象,该futuredtask对象封装了callable对象的call方法的返回值。

  iii. 使用futuretask对象作为thread对象的target,创建并启动新线程。

  iv. 调用futuretask对象的get方法来获得子线程执行结束后的返回值。

 1 public class testcallable {
 2     public static void main(string[] args) {
 3         threaddemo td = new threaddemo();
 4         //1.执行 callable 方式,需要 futuretask 实现类的支持,用于接收运算结果。
 5         futuretask<integer> result = new futuretask<>(td);
 6         new thread(result).start();
 7         //2.接收线程运算后的结果
 8         try {
 9             integer sum = result.get();  //futuretask 可用于闭锁
10             system.out.println(sum);
11             system.out.println("------------------------------------");
12         } catch (interruptedexception | executionexception e) {
13             e.printstacktrace();
14         }
15     }
16 }
17 class threaddemo implements callable<integer>{
18     public integer call() throws exception {
19         int sum = 0;
20         for (int i = 0; i <= 100000; i++) {
21             sum += i;
22         }    
23         return sum;
24     }    
25 }
 1  //创建一个线程池
 2 executorservice pool = executors.newfixedthreadpool(tasksize);
 3 // 创建多个有返回值的任务
 4 list<future> list = new arraylist<future>(); 
 5 for (int i = 0; i < tasksize; i++) { 
 6     callable c = new mycallable(i + " "); 
 7     // 执行任务并获取 future 对象
 8     future f = pool.submit(c); 
 9     list.add(f); 
10 } 
11 // 关闭线程池
12 pool.shutdown(); 
13 // 获取所有并发任务的运行结果
14 for (future f : list) { 
15     // 从 future 对象上获取任务的返回值,并输出到控制台
16     system.out.println("res:" + f.get().tostring()); 
17 }