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

相关推荐
顾林海5 分钟前
深度解析LinkedHashSet工作原理
android·java·面试
创码小奇客10 分钟前
Java 对象变形记:BeanUtils 与 MapStruct 的高阶魔法实战
java·spring boot·trae
申城异乡人22 分钟前
Spring RestTemplate使用方法总结
java
有诺千金43 分钟前
深入理解 Spring Boot 的@AutoConfiguration注解
java·spring boot·后端
代码吐槽菌44 分钟前
基于SpringBoot的律师事务所案件管理系统【附源码】
java·数据库·spring boot·后端·毕业设计
flzjkl1 小时前
【源码】【Java并发】【ReentrantLock】适合中学者体质的ReentrantLock源码阅读
java·后端
freejackman1 小时前
Java 环境配置
java·后端·java ee
bug菌1 小时前
领导安排我一小时实现一个导出功能,我竟用@Excel注解两分钟搞定!🫠
java·后端·spring
bug菌1 小时前
Swagger注解全攻略:一文搞懂 @ApiIgnore 的妙用!
java·后端·spring
bug菌1 小时前
想确保用户输入有效吗?@Size注解是你的不二之选!
java·后端·spring