【java】scala ExecutorService停止线程池的简单案例

上代码:

scala 复制代码
import org.scalatest.funsuite.AnyFunSuite
import java.util.concurrent.{ExecutorService, Executors, TimeUnit}

class ExecutorPoolTest extends AnyFunSuite {
  val threadPool: ExecutorService = Executors.newFixedThreadPool(1)

  val job: Runnable = new Runnable {
    @volatile var stop = false

    override def run(): Unit = {
      while (!stop) {
        try {
          println(s"Runnable is working, ${System.currentTimeMillis()}")
          Thread.sleep(1000)
        } catch {
          case i: InterruptedException => {
            println("Runnable encounter interrupt!")
            stop = true
          }
          case other =>
        }
      }
    }
  }


  def stopPool():Unit={
    println("ready to shutdown thread pool!")
    threadPool.shutdown()
    if (!threadPool.awaitTermination(10, TimeUnit.SECONDS)) {
      println("ready to force shutting down thread pool!")
      threadPool.shutdownNow()
    }
  }

  test("test-shutdown") {

    threadPool.execute(job)
    Thread.sleep(5000)
    stopPool()

    while (true) {
      println("main thread is still running!")
      Thread.sleep(3000)
    }
  }
}

参考文章:

如何优雅的停止线程(池)
如何优雅地停止一个线程?
ExecutorService 线程池详解
ExecutorsService.submit详解
ExecutorService的invokeAll方法详解

相关推荐
2601_9673387116 分钟前
尚硅谷2026尚硅谷Java全栈+Python智能体教程
java·人工智能
孙克旭_41 分钟前
单链表进阶实操:5 道常考面试题详细解析【Java 实现】
java·开发语言·数据结构·单链表
2601_961901701 小时前
SpringCloud2023集成Nacos2.4.3
java
玄昌盛不会编程1 小时前
LeetCode——2091. 从数组中移除最大值和最小值
java·算法·leetcode
Rain的Java大神之路1 小时前
如何保证接口幂等
java·经验分享·后端·面试·架构
吴声子夜歌1 小时前
Java——数组和集合(一)
java·开发语言
Jesse_EC1 小时前
一个看不见的字符——CRLF 如何让我的 Docker 初始化脚本"静默失踪"
java·后端
深念Y1 小时前
Nuxt 项目 Docker 构建:从 pnpm+node 迁移到全 bun
java·前端·docker
学长毕业设计1 小时前
基于SpringBoot的社区鲜奶订购系统的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
呆呆敲代码的小Y1 小时前
【游戏开发】C# 中的迭代器
java·开发语言·c#·迭代器