Java实现异步调用
一、创建线程
@Test
public void test0() throws Exception {
System.out.println("main函数开始执行");
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("===task start===");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("===task finish===");
}
});
thread.start();
System.out.println("main函数执行结束");
}
二、Future
jdk8之前的实现方式,在JUC下增加了Future
,从字面意思理解就是未来的意思,但使用起来却着实有点鸡肋,并不能实现真正意义上的异步,获取结果时需要阻塞线程,或者不断轮询。
@Test
public void test1() throws Exception {
System.out.println("main函数开始执行");
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("===task start===");
Thread.sleep(5000);
System.out.println("===task finish===");
return 3;
}
});
// 这里需要返回值时会阻塞主线程,如果不需要返回值使用是OK的。倒也还能接受
// Integer result=future.get();
System.out.println("main函数执行结束");
System.in.read();
}
三、CompletableFuture
使用原生的CompletableFuture
实现异步操作,加上对lambda的支持,可以说实现异步任务已经发挥到了极致。
@Test
public void test2() throws Exception {
System.out.println("main函数开始执行");
ExecutorService executor = Executors.newFixedThreadPool</