在开发中,咱们常常经过new thread或者实现runable接口的方式来建立线程,其实还能够经过实现Callable接口来建立线程。java
先看一下API文档中关于Callable的介绍:
web
咱们能够看出来,相较于实现Runnable接口的方式,实现Callable接口这种方法能够有返回值,而且能够抛出异常。ide
经过实现Callable接口来建立线程,须要依赖FutureTask实现类的支持,用于接收运算结果。svg
测试示例:测试
package com.li.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/** * 1.相较于实现Runnable接口的方式,方法能够有返回值,而且能够抛出异常 * 2.须要依赖FutureTask实现类的支持,用于接收运算结果 */
public class TestCallable {
public static void main(String[] args) {
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> result = new FutureTask<Integer>(ctt);
new Thread(result).start();
Integer sum;
try {
sum = result.get();
System.out.println("-->" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class CallableThreadTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 100;
System.out.println("CurrentThread-->" + Thread.currentThread());
Thread.sleep(2000);
return sum;
}
}
在线程池中,通常和ExecutorService配合来使用。测试示例:spa
package com.li.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestCallable {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
System.out.println("主线程开始。。。" + Thread.currentThread());
ExecutorService executor = Executors.newCachedThreadPool();
Future<Integer> result = executor.submit(new CallableTask());
executor.shutdown();
Integer i = result.get();
System.out.println("主线程结束。。。");
System.out.println("主线程获取子线程结果为:" + i);
}
}
class CallableTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 100;
System.out.println("子线程开始计算。。。" + Thread.currentThread());
Thread.sleep(3000);
System.out.println("子线程结束计算。。。");
return sum;
}
}