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

相关推荐
967738 分钟前
理解IOC控制反转和spring容器,@Autowired的参数的作用
java·sql·spring
SY_FC38 分钟前
实现一个父组件引入了子组件,跳转到其他页面,其他页面返回回来重新加载子组件函数
java·前端·javascript
耀耀_很无聊1 小时前
09_Jenkins安装JDK环境
java·运维·jenkins
ノBye~1 小时前
Centos7.6 Docker安装redis(带密码 + 持久化)
java·redis·docker
黑臂麒麟1 小时前
openYuanrong:多语言运行时独立部署以库集成简化 Serverless 架构 & 拓扑感知调度:提升函数运行时性能
java·架构·serverless·openyuanrong
XiaoLeisj1 小时前
Android Jetpack 页面架构实战:从 LiveData、ViewModel 到 DataBinding 的生命周期管理与数据绑定
android·java·架构·android jetpack·livedata·viewmodel·databinding
⑩-1 小时前
为什么要用消息队列?使用场景?
java·rabbitmq
似水明俊德1 小时前
01-C#.Net-泛型-面试题
java·开发语言·面试·c#·.net
Allnadyy2 小时前
【C++项目】从零实现高并发内存池(一):核心原理与设计思路
java·开发语言·jvm
浑水摸鱼仙君2 小时前
SpringSecurity和Flux同时使用报未认证问题
java·ai·flux·springsecurity·springai