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

相关推荐
TAEHENGV几秒前
外观设置模块 Cordova 与 OpenHarmony 混合开发实战
java·运维·服务器
Vic101013 分钟前
Spring AOP 高级陷阱:为什么 @Before 修改参数是“伪修改“?
java·python·spring
Violet_YSWY9 分钟前
domain文件夹
java
最贪吃的虎9 分钟前
JVM扫盲:内存模型
java·运维·jvm·后端
weixin_4397062510 分钟前
如何使用JAVA进行MCP服务创建以及通过大模型进行调用
java·开发语言
AAA简单玩转程序设计10 分钟前
Java 进阶基础:这 3 个知识点,新手到高手的必经之路!
java
ONExiaobaijs11 分钟前
基于Spring Boot的校园闲置物品交易系统
java·spring boot·后端
爬山算法16 分钟前
Hibernate(2)Hibernate的核心组件有哪些?
java·后端·hibernate
AAA简单玩转程序设计17 分钟前
Java 进阶基础: “低调但致命” 的基础坑!
java
L0CK28 分钟前
web后端开发完结---Java后端开发架构深度解析
java