当前位置: 移动技术网 > IT编程>开发语言>Java > 创建线程之三:实现Callable接口

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

2019年11月22日  | 移动技术网IT编程  | 我要评论

通过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 } 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网