Callable
实现线程的方式主要有三种方式;
1;继承Thread;
2:实现Runnable 接口;
3:线程Callable 接口
ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。
1:可以有返回值
2:可以抛出异常
3:方法不同 Runnable的方法是run方法,Callable的方法是call方法;
代码测试:
package com.baidu.Callable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// new Thread(new Runnable()).start();
// new Thread(new FutureTask<V>()).start();
// new Thread(new FutureTask<V>( Callable )).start();
MyThresd myThresd = new MyThresd();
//适配类
FutureTask futureTask = new FutureTask(myThresd);
new Thread(futureTask,"A").start();
Integer integer = (Integer) futureTask.get();//获取返回的结果;
System.out.println(integer);
}
}
class MyThresd implements Callable<Integer>{
@Override
public Integer call() {
System.out.println("call()");
return 1024;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71867.html