1、开线程
public class ThreadTest {
public void test() {
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
2、Future
public class FutureTest {
public void test() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> submit = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "hello";
}
});
String s = submit.get();
}
}
3、CompletableFuture
public class CompletableFutureTest {
public void test() {
ExecutorService executorService = Executors.newFixedThreadPool(1);
CompletableFuture<String> c = CompletableFuture.supplyAsync(new Supplier<String>() {
@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注解
public class AsyncTest {
@Async
public void test() throws InterruptedException {
Thread.sleep(1000);
}
@Async
public Future<String> testReturn() throws InterruptedException {
Thread.sleep(1000);
return new AsyncResult<>("hello");
}
}
原文链接