【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方法详解

相关推荐
hzc09876543217 小时前
Spring Integration + MQTT
java·后端·spring
前路不黑暗@8 小时前
Java项目:Java脚手架项目的公共模块的实现(二)
java·开发语言·spring boot·学习·spring cloud·maven·idea
人道领域8 小时前
Spring核心注解全解析
java·开发语言·spring boot
金牌归来发现妻女流落街头9 小时前
日志级别是摆设吗?
java·spring boot·日志
MOONICK9 小时前
C#基础入门
java·开发语言
程序员小假10 小时前
我们来说一下虚拟内存的概念、作用及实现原理
java·后端
悠哉清闲10 小时前
Future
java·开发语言·kotlin
徐同保10 小时前
python如何手动抛出异常
java·前端·python
极客先躯11 小时前
高级java每日一道面试题-2025年7月02日-基础篇[LangChain4j]-什么是 AiServices?它是如何简化 LLM 应用开发的?
java·开发语言
摇滚侠11 小时前
JWT 是 token 的一种格式,我的理解对吗?
java·人工智能·intellij-idea·spring ai·springaialibaba