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

相关推荐
SUPER526621 分钟前
FastApi项目启动失败 got an unexpected keyword argument ‘loop_factory‘
java·服务器·前端
咕噜咕噜啦啦1 小时前
Eclipse集成开发环境的使用
java·ide·eclipse
光军oi4 小时前
全栈开发杂谈————关于websocket若干问题的大讨论
java·websocket·apache
weixin_419658314 小时前
Spring 的统一功能
java·后端·spring
小许学java4 小时前
Spring AI-流式编程
java·后端·spring·sse·spring ai
haogexiaole5 小时前
Java高并发常见架构、处理方式、api调优
java·开发语言·架构
EnCi Zheng5 小时前
@ResponseStatus 注解详解
java·spring boot·后端
wdfk_prog5 小时前
闹钟定时器(Alarm Timer)初始化:构建可挂起的定时器基础框架
java·linux·数据库
怎么没有名字注册了啊6 小时前
C++后台进程
java·c++·算法
z日火6 小时前
Java 泛型
java·开发语言