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

相关推荐
愚公移码19 小时前
蓝凌EKP产品:理解连接池、理解Hikari和Druid 区别
java·oracle·hibernate
天远Date Lab19 小时前
构建金融级风控中台:Java Spring Boot 集成天远借贷风险探查 API 实战
java·大数据·spring boot·金融
Han.miracle20 小时前
数据结构与算法-012
java·开发语言
计算机毕设指导620 小时前
基于微信小程序+django连锁火锅智慧餐饮管理系统【源码文末联系】
java·后端·python·mysql·微信小程序·小程序·django
宋情写20 小时前
Java基础篇01-环境搭建+入门体验
java·开发语言
悟能不能悟20 小时前
java list=null,可以stream吗
java·windows·list
cike_y20 小时前
Mybatis-万能的Map&模糊查询
java·开发语言·mybatis·安全开发
开开心心_Every20 小时前
无广告干扰:简单好用文字LOGO设计工具
xml·java·网络·数据库·华为od·华为云·excel
古城小栈20 小时前
GitHub Copilot for Java:上下文感知重构建议实操
java·github·copilot
秋邱21 小时前
Java面向对象进阶:封装、继承、多态的实现逻辑与实战案例
java·开发语言·后端·spring cloud·ar·restful