Java timeout怎樣避免影響并發(fā)

小樊
82
2024-07-20 09:30:42

在Java中,可以通過使用ExecutorService來(lái)管理多個(gè)并發(fā)任務(wù),并設(shè)置超時(shí)時(shí)間來(lái)避免影響并發(fā)。以下是一個(gè)示例代碼:

ExecutorService executor = Executors.newFixedThreadPool(10); // 創(chuàng)建一個(gè)固定大小的線程池

Future<String> future = executor.submit(() -> {
    // 執(zhí)行需要超時(shí)控制的任務(wù)
    Thread.sleep(5000); // 模擬耗時(shí)操作
    return "Task completed";
});

try {
    String result = future.get(3, TimeUnit.SECONDS); // 設(shè)置超時(shí)時(shí)間為3秒
    System.out.println(result);
} catch (TimeoutException e) {
    System.out.println("Task timeout");
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}

executor.shutdown();

在上面的示例中,我們使用ExecutorService創(chuàng)建一個(gè)固定大小的線程池,并提交一個(gè)需要超時(shí)控制的任務(wù)。通過調(diào)用future.get(timeout, unit)方法可以設(shè)置任務(wù)的超時(shí)時(shí)間,如果任務(wù)在超時(shí)時(shí)間內(nèi)未完成,則會(huì)拋出TimeoutException異常。最后,記得調(diào)用executor.shutdown()來(lái)關(guān)閉線程池。這樣可以避免單個(gè)任務(wù)的超時(shí)影響到其他并發(fā)任務(wù)的執(zhí)行。

0