Logo
Section 1 / 12

Executor Framework

掌握 ExecutorService,以高效管理线程池,解耦任务提交与执行,并安全地关闭执行器。

导入

Executor Framework

掌握 ExecutorService,以高效管理线程池,解耦任务提交与执行,并安全地关闭执行器。

...
The ExecutorService workflow
1import java.util.concurrent.ExecutorService; 2import java.util.concurrent.Executors; 3import java.util.concurrent.TimeUnit; 4 5public class ThreadPool { 6 public static void main(String[] args) { 7 // Create a pool with only 2 threads 8 ExecutorService executor = Executors.newFixedThreadPool(2); 9 10 try { 11 // Submit 5 tasks 12 for (int i = 1; i <= 5; i++) { 13 int taskId = i; 14 executor.execute(() -> { 15 String threadName = Thread.currentThread().getName(); 16 System.out.println("Task " + taskId + " running on " + threadName); 17 }); 18 } 19 } finally { 20 // Always shut down the executor 21 executor.shutdown(); 22 try { 23 // Wait briefly for tasks to finish to ensure we see the output 24 executor.awaitTermination(5, TimeUnit.SECONDS); 25 } catch (InterruptedException e) { 26 Thread.currentThread().interrupt(); 27 } 28 } 29 } 30}

代码示例

1Task 1 running on pool-1-thread-1 2Task 2 running on pool-1-thread-2 3Task 3 running on pool-1-thread-1 4Task 4 running on pool-1-thread-2 5Task 5 running on pool-1-thread-1
1import java.util.concurrent.Executors; 2import java.util.concurrent.ScheduledExecutorService; 3import java.util.concurrent.TimeUnit; 4 5public class SchedulingExample { 6 public static void main(String[] args) { 7 // Create a scheduled pool with 1 thread 8 ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 9 10 System.out.println("Scheduler started."); 11 12 // 1. One-time execution after a 2-second delay 13 scheduler.schedule(() -> { 14 System.out.println("Delayed task executed after 2 seconds."); 15 }, 2, TimeUnit.SECONDS); 16 17 // 2. Periodic execution: Start immediately, repeat every 1 second 18 scheduler.scheduleAtFixedRate(() -> { 19 System.out.println("Heartbeat..."); 20 }, 0, 1, TimeUnit.SECONDS); 21 22 // Let the periodic task run for a while 23 try { 24 Thread.sleep(5000); 25 } catch (InterruptedException e) { 26 Thread.currentThread().interrupt(); 27 } 28 29 System.out.println("Shutting down..."); 30 scheduler.shutdown(); 31 } 32}
1import java.util.concurrent.ExecutorService; 2import java.util.concurrent.Executors; 3import java.util.concurrent.TimeUnit; 4 5public class Lifecycle { 6 public static void main(String[] args) { 7 long startTime = System.currentTimeMillis(); 8 ExecutorService executor = Executors.newSingleThreadExecutor(); 9 10 executor.execute(() -> { 11 try { 12 Thread.sleep(1000); // Simulate 1 second of work 13 System.out.println("Task completed."); 14 } catch (InterruptedException e) { 15 Thread.currentThread().interrupt(); 16 } 17 }); 18 19 System.out.println("Main thread initiating shutdown..."); 20 executor.shutdown(); // Stop accepting new tasks 21 22 try { 23 // Wait up to 5 seconds for tasks to finish 24 if (executor.awaitTermination(5, TimeUnit.SECONDS)) { 25 long duration = System.currentTimeMillis() - startTime; 26 System.out.println("Pool closed. Total time: " + duration + "ms"); 27 } else { 28 System.out.println("Tasks did not finish in time."); 29 } 30 } catch (InterruptedException e) { 31 Thread.currentThread().interrupt(); 32 } 33 } 34}
1import java.util.concurrent.ExecutorService; 2import java.util.concurrent.Executors; 3import java.util.concurrent.RejectedExecutionException; 4 5public class ShutdownVerification { 6 public static void main(String[] args) { 7 ExecutorService executor = Executors.newFixedThreadPool(1); 8 9 executor.shutdown(); 10 System.out.println("Executor shut down."); 11 12 try { 13 // Attempt to submit a new task 14 executor.execute(() -> System.out.println("This will not run.")); 15 } catch (RejectedExecutionException e) { 16 System.out.println("Verified: Task was rejected."); 17 } 18 } 19}

线程与并发

Futures 和 Callables