创建线程的方式:3.实现Callable接口
实现Callable接口
-
实现Callable接口,需要返回值类型:implements Callable
-
重写call方法,需要抛出异常 :public Boolean call() throws Exception {}
-
创建目标对象 :CallableTest callableTest = new CallableTest();
-
创建执行服务:ExecutorService service = Executors.newFixedThreadPool(1);
-
提交执行:Future future = service.submit(callableTest);
-
获取结果:boolean result = future.get();
-
关闭服务:service.shutdownNow();
package test;
import java.util.concurrent.*;
//线程创建方式三:实现callable接口
public class CallableTest implements Callable<Boolean> {
//坐标
private Integer index;
public CallableTest(Integer index) {
this.index = index;
}
@Override
public Boolean call() throws Exception {
System.out.println("执行了call方法" + index);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableTest callableTest1 = new CallableTest(1);
CallableTest callableTest2 = new CallableTest(2);
CallableTest callableTest3 = new CallableTest(3);
//创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> future1 = service.submit(callableTest1);
Future<Boolean> future2 = service.submit(callableTest2);
Future<Boolean> future3 = service.submit(callableTest3);
//获取结果
boolean result1 = future1.get();
boolean result2 = future2.get();
boolean result3 = future3.get();
//关闭服务
service.shutdownNow();
}
}
callable的好处:
-
可以定义返回值
-
可以抛出异常