Java多線程execute如何實(shí)現(xiàn)異步執(zhí)行

小樊
81
2024-09-29 12:50:02

在Java中,通過(guò)使用ExecutorService接口和其實(shí)現(xiàn)類(如ThreadPoolExecutor)可以輕松地實(shí)現(xiàn)多線程的異步執(zhí)行。以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用execute()方法實(shí)現(xiàn)異步執(zhí)行:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncExecutionExample {

    public static void main(String[] args) {
        // 創(chuàng)建一個(gè)固定大小的線程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        // 提交任務(wù)到線程池,并異步執(zhí)行
        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 {
                    // 模擬任務(wù)執(zhí)行耗時(shí)
                    Thread.sleep((long) (Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskNumber + " is completed in thread " + Thread.currentThread().getName());
            });
        }

        // 關(guān)閉線程池
        executorService.shutdown();
    }
}

在這個(gè)示例中,我們創(chuàng)建了一個(gè)固定大小為5的線程池。然后,我們提交了10個(gè)任務(wù)到線程池,并使用execute()方法異步執(zhí)行它們。每個(gè)任務(wù)都會(huì)在單獨(dú)的線程中運(yùn)行,從而實(shí)現(xiàn)了異步執(zhí)行。

需要注意的是,execute()方法不會(huì)返回任務(wù)的結(jié)果,因此如果你需要獲取任務(wù)的結(jié)果,可以考慮使用FutureCompletableFuture。

0