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

相关推荐
狼爷1 天前
破解 JetBrains 的学生,后来都成了它的 “推销员”:一场用习惯换市场的长期战
java·jetbrains
.豆鲨包1 天前
【Android】Viewpager2实现无限轮播图
android·java
BXCQ_xuan1 天前
软件工程实践二:Spring Boot 知识回顾
java·spring boot·后端
老赵的博客1 天前
c++ unqiue指针
java·jvm·c++
wuxuanok1 天前
SpringBoot -原理篇
java·spring boot·spring
柿蒂1 天前
从if-else和switch,聊聊“八股“的作用
android·java·kotlin
二饭1 天前
Spring Boot 项目启动报错:MongoSocketOpenException 连接被拒绝排查日记
java·spring boot·后端
懒虫虫~1 天前
通过内存去重替换SQL中distinct,优化SQL查询效率
java·sql·慢sql治理
鼠鼠我捏,要死了捏1 天前
基于Redisson的分布式锁原理深度解析与性能优化实践指南
java·高并发·redisson
backordinary1 天前
微服务学习笔记25版
java·java-ee