在Java中,通過使用ExecutorService
接口和其實現類(如ThreadPoolExecutor
)可以輕松地實現多線程的異步執行。以下是一個簡單的示例,展示了如何使用execute()
方法實現異步執行:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsyncExecutionExample {
public static void main(String[] args) {
// 創建一個固定大小的線程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
// 提交任務到線程池,并異步執行
for (int i = 0; i < 10; i++) {
final int taskNumber = i;
executorService.execute(() -> {
System.out.println("Task " + taskNumber + " is being executed in thread " + Thread.currentThread().getName());
try {
// 模擬任務執行耗時
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + taskNumber + " is completed in thread " + Thread.currentThread().getName());
});
}
// 關閉線程池
executorService.shutdown();
}
}
在這個示例中,我們創建了一個固定大小為5的線程池。然后,我們提交了10個任務到線程池,并使用execute()
方法異步執行它們。每個任務都會在單獨的線程中運行,從而實現了異步執行。
需要注意的是,execute()
方法不會返回任務的結果,因此如果你需要獲取任務的結果,可以考慮使用Future
或CompletableFuture
。