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

相关推荐
爱吃山竹的大肚肚14 小时前
优化SQL:如何使用 EXPLAIN
java·数据库·spring boot·sql·spring
行思理14 小时前
FastAdmin新手教程
java·开发语言·fastadmin
向上的车轮14 小时前
Apache Camel 与 Spring Integration的区别是什么?
java·spring·apache
nsjqj14 小时前
JavaEE初阶:计算机是如何工作的
java·java-ee
URBBRGROUN46714 小时前
Spring AI Alibaba入门
java·人工智能·spring
她和夏天一样热14 小时前
【实战篇】设计模式在开发中的真实应用
java·开发语言·设计模式
小帅学编程14 小时前
设计模式笔记
java
ss27314 小时前
线程池工作机制:从任务提交到执行的完整决策流程
java·开发语言
yaoxin52112315 小时前
276. Java Stream API - 使用 flatMap 和 mapMulti 清理数据并转换类型
java·开发语言·windows