在JDK8下异步执行可以考虑使用CompletableFuture,下面是一个很简单的例子。
private static void test() {
CompletableFuture cf = CompletableFuture.runAsync(()->{
System.out.println(Thread.currentThread() + " start,time->" + System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + " exit,time->" + System.currentTimeMillis());
});
}
public static void main(String[] args) {
System.out.println(Thread.currentThread() + " main1,time->" + System.currentTimeMillis());
test();
System.out.println(Thread.currentThread() + " main2,time->" + System.currentTimeMillis());
try {
Thread.sleep(20000); // 如果没有这个,main进程会在CompletableFuture执行完之前就退出,导致看不到CompletableFuture里面的输出
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + " mainExit,time->" + System.currentTimeMillis());
}
输出:
Thread[main,5,main] main1,time->1645580342869
Thread[main,5,main] main2,time->1645580342906
Thread[ForkJoinPool.commonPool-worker-9,5,main] start,time->1645580342906
Thread[ForkJoinPool.commonPool-worker-9,5,main] exit,time->1645580344907
Thread[main,5,main] mainExit,time->1645580362907
如果有返回值可以这样:
private static void test2() {
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread() + " start2,time->" + System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + " exit,time->" + System.currentTimeMillis());
return "ddd";
});
try {
String result = cf2.get();
System.out.println(Thread.currentThread() + " exit2,result->" + result);
} catch (Exception e) {
e.printStackTrace();
}
}