Java线程池ExecutorService学习和使用

示例1:使用ScheduledExecutorService进行定时任务调度
import java.util.concurrent.*;

public class ScheduledExecutorServiceExample {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);

        Runnable task = () -> System.out.println("Executing Task at " + System.nanoTime());

        scheduledExecutorService.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS);

        try {
            Thread.sleep(10000);  // 让调度执行一段时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        scheduledExecutorService.shutdown();
    }
}
​
 
 
示例2:使用线程池执行大量任务并等待其完成
import java.util.concurrent.*;

public class BulkTaskExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        Callable<String> task = () -> {
            TimeUnit.SECONDS.sleep(1);
            return Thread.currentThread().getName();
        };

        List<Future<String>> futures = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            futures.add(executorService.submit(task));
        }

        futures.forEach(future -> {
            try {
                System.out.println(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });

        executorService.shutdown();
    }
}
posted @ 2025-05-09 11:29  hczyydqq  阅读(9)  评论(0)    收藏  举报