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

相关推荐
张柏慈6 小时前
Java性能优化:实战技巧与案例解析
java
天“码”行空6 小时前
简化Lambda——方法引用
java·开发语言
带刺的坐椅7 小时前
MCP 进化:让静态 Tool 进化为具备“上下文感知”的远程 Skills
java·ai·llm·agent·solon·mcp·tool-call·skills
java1234_小锋7 小时前
Java线程之间是如何通信的?
java·开发语言
张张努力变强7 小时前
C++ Date日期类的设计与实现全解析
java·开发语言·c++·算法
while(1){yan}8 小时前
Spring事务
java·数据库·spring boot·后端·java-ee·mybatis
毕设源码-赖学姐8 小时前
【开题答辩全过程】以 高校社团管理平台为例,包含答辩的问题和答案
java
余瑜鱼鱼鱼9 小时前
线程和进程的区别和联系
java·开发语言·jvm
小唐同学爱学习9 小时前
如何解决海量数据存储
java·数据库·spring boot·mysql
962464i9 小时前
SBE(simple-binary-encoding)-Demo
java