线程工具类

该代码片段展示了如何优雅地和正常地关闭Java的ExecutorService。`gracefulShutdown`方法首先尝试平滑停止服务,等待已提交任务完成,如果超时则取消未开始的任务并中断阻塞操作。`normalShutdown`方法则直接调用shutdownNow并等待一定时间,确保服务关闭。这两个方法都处理了中断异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Threads {

   /**
    * sleep等待,单位为毫秒,忽略InterruptedException.
    */
   public static void sleep(long millis) {
      try {
         Thread.sleep(millis);
      } catch (InterruptedException e) {
         // Ignore.
         return;
      }
   }

   /**
    * sleep等待,忽略InterruptedException.
    */
   public static void sleep(long duration, TimeUnit unit) {
      try {
         Thread.sleep(unit.toMillis(duration));
      } catch (InterruptedException e) {
         // Ignore.
         return;
      }
   }

   /**
    * 按照ExecutorService JavaDoc示例代码编写的Graceful Shutdown方法.
    * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
    * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
    * 如果仍人超時,則強制退出.
    * 另对在shutdown时线程本身被调用中断做了处理.
    */
   public static void gracefulShutdown(ExecutorService pool, int shutdownTimeout, int shutdownNowTimeout,
         TimeUnit timeUnit) {
      pool.shutdown(); // Disable new tasks from being submitted
      try {
         // Wait a while for existing tasks to terminate
         if (!pool.awaitTermination(shutdownTimeout, timeUnit)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(shutdownNowTimeout, timeUnit)) {
               System.err.println("Pool did not terminated");
            }
         }
      } catch (InterruptedException ie) {
         // (Re-)Cancel if current thread also interrupted
         pool.shutdownNow();
         // Preserve interrupt status
         Thread.currentThread().interrupt();
      }
   }

   /**
    * 直接调用shutdownNow的方法, 有timeout控制.取消在workQueue中Pending的任务,并中断所有阻塞函数.
    */
   public static void normalShutdown(ExecutorService pool, int timeout, TimeUnit timeUnit) {
      try {
         pool.shutdownNow();
         if (!pool.awaitTermination(timeout, timeUnit)) {
            System.err.println("Pool did not terminated");
         }
      } catch (InterruptedException ie) {
         Thread.currentThread().interrupt();
      }
   }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值