【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 分钟前
Spring Boot3零基础教程,响应式编程的模型,笔记109
java·spring boot·笔记
wfsm32 分钟前
flowable使用01
java·前端·servlet
员大头硬花生37 分钟前
七、InnoDB引擎-架构-后台线程
java·数据库·mysql
拾荒的小海螺1 小时前
JAVA:Spring Boot3 新特性解析的技术指南
java·开发语言·spring boot
暹罗软件开发1 小时前
快速搭建分布式链路追踪系统:SkyWalking全攻略
java·skywalking
.格子衫.1 小时前
Maven中的配置
java·maven
L.EscaRC2 小时前
Spring Boot 自定义组件深度解析
java·spring boot·后端
pengzhuofan2 小时前
IntelliJ IDEA 常用快捷键
java·ide·intellij-idea
ANGLAL2 小时前
17.MyBatis动态SQL语法整理
java·sql·mybatis