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;
}
}