码迷,mamicode.com
首页 > 其他好文 > 详细

实现Callable接口,并与Future结合使用

时间:2019-08-15 19:24:05      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:返回值   接口   rgs   com   new   void   execution   integer   string   


实现步骤:

创建 Callable 接口的实现类,并实现 call() 方法,该 call() 方法将作为线程执行体,并且有返回值。

创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象,该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值。

使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。

调用Tread对象的start()方法启动线程,调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。

实例:

public class CallableThreadTest implements Callable<Integer> {
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {

FutureTask<Integer> ft = new FutureTask<>(new CallableThreadTest(http://www.amjmh.com/v/));
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);
if(i==20)
{
new Thread(ft).start();
}
}

System.out.println("子线程的返回值:"+ft.get());

}
}

实现Callable接口,并与Future结合使用

标签:返回值   接口   rgs   com   new   void   execution   integer   string   

原文地址:https://www.cnblogs.com/liyanyan665/p/11359758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!