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

相关推荐
一个尚在学习的计算机小白2 分钟前
java集合
java·开发语言
IUGEI10 分钟前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
q***136114 分钟前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
z***I39414 分钟前
Java桌面应用案例
java·开发语言
r***123835 分钟前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
间彧38 分钟前
Java进程内存深度解析:从JVM组件内存到RSS的全面视角
java
间彧1 小时前
对比GraalVM Native Image与传统JVM,在内存管理方面各自适合哪些具体业务场景?
java
daidaidaiyu1 小时前
Spring IOC 源码学习一 基本姿势
java·spring
LSL666_1 小时前
SpringBoot自动配置类
java·spring boot·后端·自动配置类
甜鲸鱼2 小时前
Java与MySQL中的枚举(Enum)
java·mysql