Java线程池用法实战案例分析
更新:HHH   时间:2023-1-8


本文实例讲述了Java线程池用法。分享给大家供大家参考,具体如下:

一 使用newSingleThreadExecutor创建一个只包含一个线程的线程池

1 代码

import java.util.concurrent.*;
public class executorDemo
{
  public static void main( String[] args )
  {    
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
      String threadName = Thread.currentThread().getName();
      System.out.println("Hello " + threadName);
    }); 
  }
}

2 运行

Hello pool-1-thread-1

二 含有终止方法的线程池

1 代码

import java.util.concurrent.*;
public class executorShutdownDemo {
  public static void main( String[] args ) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
      String threadName = Thread.currentThread().getName();
      System.out.println("Hello " + threadName);
    });
    try {
      TimeUnit.SECONDS.sleep(3);
      System.out.println("尝试关闭线程执行器...");
      executor.shutdown();
      executor.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      System.err.println("关闭任务被中断!");
    } finally {
      if (!executor.isTerminated()) {
        System.err.println("取消未完成的任务");
        executor.shutdownNow();
      }
      System.out.println("任务关闭完成");
    }
  }
}

2 运行

Hello pool-1-thread-1
尝试关闭线程执行器...
任务关闭完成

3 说明

shutdown只是将线程池的状态设置为SHUTWDOWN状态,正在执行的任务会继续执行下去,没有被执行的则中断。

shutdownNow则是将线程池的状态设置为STOP,正在执行的任务则被停止,没被执行任务的则返回。

举个工人吃包子的例子:一个厂的工人(Workers)正在吃包子(可以理解为任务)。

假如接到shutdown的命令,那么这个厂的工人们则会把手头上的包子给吃完,没有拿到手里的笼子里面的包子则不能吃!

而如果接到shutdownNow的命令以后呢,这些工人们立刻停止吃包子,会把手头上没吃完的包子放下,更别提笼子里的包子了。

awaitTermination(long timeOut, TimeUnit unit)

当前线程阻塞,直到

  • 等所有已提交的任务(包括正在跑的和队列中等待的)执行完
  • 或者等超时时间到
  • 或者线程被中断,抛出InterruptedException

然后返回true。

更多java相关内容感兴趣的读者可查看本站专题:《Java进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

返回编程语言教程...