多執行緒程式設計ExecutorService用法

阿昭發表於2024-10-30

以下內容均來自ChatGPT提供的示例,用於自學

ExecutorService 是 Java 中用於管理和控制執行緒池的介面,通常用來簡化多執行緒程式設計。它提供了一組方法,允許我們在非同步任務執行完畢後關閉執行緒池、排程任務等操作。以下是幾個常見的使用場景和示例程式碼:

1. 使用 ExecutorService 執行簡單任務

透過 Executors 建立一個固定大小的執行緒池,然後提交任務執行。

public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for(int i= 0; i < 5; i ++){
int taskId = i;
executorService.submit(()-> {
System.out.println("start executing task " + taskId + ". Thread:" + Thread.currentThread().getName());
try {
Thread.sleep(1000); //Simulate task execution time
System.out.println("end executing task " + taskId + ". Thread:" + Thread.currentThread().getName());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
executorService.shutdown();
}

列印輸出

> Task :ExecutorServiceExample.main()
start executing task 2. Thread:pool-1-thread-3
start executing task 0. Thread:pool-1-thread-1
start executing task 1. Thread:pool-1-thread-2
end executing task 0. Thread:pool-1-thread-1
end executing task 1. Thread:pool-1-thread-2
end executing task 2. Thread:pool-1-thread-3
start executing task 3. Thread:pool-1-thread-2
start executing task 4. Thread:pool-1-thread-1
end executing task 3. Thread:pool-1-thread-2
end executing task 4. Thread:pool-1-thread-1

2. 使用 CallableFuture 獲取任務結果

Callable 是一種可以返回結果的任務,而 Future 則用來獲取該任務的執行結果。

public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
//Create Callable task
Callable<String> task = () -> {
System.out.println("start task : "+ Thread.currentThread().getName());
Thread.sleep(2000); //Simulate task execution time
System.out.println("end task : "+ Thread.currentThread().getName());
return "Task completed";
};
//Submit task and get future
Future<String> feature = executorService.submit(task);
System.out.println("start feature : "+ Thread.currentThread().getName());
try {
//waiting for task results
String result = feature.get();
System.out.println("task result: " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}

> Task :ExecutorServiceExample.main()
start task : pool-1-thread-1
start feature : main
end task : pool-1-thread-1
task result: Task completed

3. 批次提交任務並等待所有任務完成

invokeAll 方法可以一次性提交多個任務,並等待所有任務完成。

public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Callable<String>> taskList = new ArrayList<>();
//Create multiple tasks
for(int i= 0; i < 5; i ++){
int taskId = i;
taskList.add(() -> {
System.out.println("start task " + taskId + ". Thread:" + Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println("end task " + taskId + ". Thread:" + Thread.currentThread().getName());
return "Task " + taskId + " completed";
});
}
try {
//Execute all tasks
List<Future<String>> results = executorService.invokeAll(taskList);
//get task results
for(Future<String> future:results){
System.out.println(future.get());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
executorService.shutdown();
}
}

> Task :ExecutorServiceExample.main()
start task 1. Thread:pool-1-thread-2
start task 0. Thread:pool-1-thread-1
start task 2. Thread:pool-1-thread-3
end task 0. Thread:pool-1-thread-1
start task 3. Thread:pool-1-thread-1
end task 2. Thread:pool-1-thread-3
end task 1. Thread:pool-1-thread-2
start task 4. Thread:pool-1-thread-3
end task 4. Thread:pool-1-thread-3
end task 3. Thread:pool-1-thread-1
Task 0 completed
Task 1 completed
Task 2 completed
Task 3 completed
Task 4 completed

4. 定時任務

可以使用 ScheduledExecutorService 來排程定時任務,以下示例展示瞭如何每隔一段時間執行一次任務。

public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
// Execute tasks every 2 seconds
scheduler.scheduleAtFixedRate(() -> {
System.out.println("Execute scheduled tasks, time:" + System.currentTimeMillis());
}, 0, 2, TimeUnit.SECONDS);

// Close after running for 10 seconds
scheduler.schedule(() -> {
scheduler.shutdown();
}, 10, TimeUnit.SECONDS);
}

> Task :ExecutorServiceExample.main()
Execute scheduled tasks, time:1730271628977
Execute scheduled tasks, time:1730271630985
Execute scheduled tasks, time:1730271632983
Execute scheduled tasks, time:1730271634984
Execute scheduled tasks, time:1730271636984
Execute scheduled tasks, time:1730271638980

相關文章