java实现异步的几种方法
985
java实现异步的4种方法:1、开线程;2、Future;3、CompletableFuture;4、Async注解
1、开线程
- 开线程
*/
public class ThreadTest { public void test() {
new Thread(() -> {
//做处理
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
2、Future
/**
- Future
*/
public class FutureTest {
public void test() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future submit = executorService.submit(new Callable() {
@Override
public String call() throws Exception {
//做处理
Thread.sleep(1000);
return “hello”;
}
});//如果需要返回值的话,会阻塞主线程。 String s = submit.get();
}
}
3、CompletableFuture
/**
- CompletableFuture
*/
public class CompletableFutureTest {
public void test() {
ExecutorService executorService = Executors.newFixedThreadPool(1);
CompletableFuture c = CompletableFuture.supplyAsync(new Supplier() {
@Override
public String get() {
//做处理
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return “hello”;
}
}, executorService);c.thenAccept(item -> System.out.println(item));
}
}
4、Async
/**
- Async注解:要在Spring中使用。
- 1、首先在启动类上开启注解@EnableAsync
- 2、然后需要异步操作的方法上加上@Async
*/
public class AsyncTest {
@Async
public void test() throws InterruptedException {
//做处理
Thread.sleep(1000);
} /**- 如果需要返回值的话,通过AsyncResult进行封装
*/
@Async
public Future testReturn() throws InterruptedException {
//做处理
Thread.sleep(1000);
return new AsyncResult<>(“hello”);
}
}
- 如果需要返回值的话,通过AsyncResult进行封装