Java并发工具库:ExecutorService的详细用法

原创 蔚落 2024-12-12 02:39 31阅读 0赞

Java的ExecutorService是处理线程并发的重要工具。它提供了一种方式来管理和调度线程任务。

下面是一些ExecutorService的基本用法:

  1. 创建ExecutorService实例:
    1. ExecutorService executor = Executors.newFixedThreadPool(5); // 创建固定大小的线程池
  2. 提交任务到线程池:
    1. Runnable task = () -> {
    2. System.out.println("Task is running by thread.");
    3. try {
    4. Thread.sleep(2000);
    5. } catch (InterruptedException e) {
    6. e.printStackTrace();
    7. }
    8. };
    9. executor.submit(task); // 将任务提交给线程池执行
  3. 关闭ExecutorService:
    1. // 提交最后一个任务,然后关闭线程池
    2. executor.submit(() -> {
    3. System.out.println("Last task submitted before shutdown.");
    4. executor.shutdown(); // 关闭线程池
    5. try {
    6. if (!executor.isTerminated()) { // 确保线程池已完全终止(可能需要等待)
    7. System.err.println("ExecutorService has not terminated properly.");
    8. }
    9. } catch (InterruptedException e) {
    10. e.printStackTrace();
    11. }
    12. }));
    以上就是ExecutorService的基本用法。在实际项目中,可能会根据需求和场景调整这些用法。
文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,31人围观)

还没有评论,来说两句吧...

相关阅读