这里采用hutool的ThreadUtil来开启线程
1.线程类实现Callable接口
import java.util.concurrent.Callable;
public class MyThread implements Callable<Integer> {
private Integer a;
public MyThread(Integer a) {
this.a = a;
}
@Override
//计算一个数+3的结果并且返回
public Integer call() throws Exception {
return a+3;
}
}
Callable中的泛型用来控制返回的结果
用线程池开启线程
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建线程池
ExecutorService service = ThreadUtil.newSingleExecutor();
Integer a = 5;
int b = 6;
//创建线程并放入线程池
//(这里只是开的一个子线程放入线程池,没有体现线程池的作用)
Future<Integer> future = service.submit(new MyThread(a));
//获取结果,future.get()会等待线程的结果
System.out.println(b+future.get());
//关闭线程池
service.shutdown();
}
}