以下内容均来自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. 使用 Callable
和 Future
获取任务结果
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