【java】scala ExecutorService停止线程池的简单案例 - class ExecutorPoolTest extends AnyFunSuite {

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力 👁️ 390 次阅读

【java】scala ExecutorService停止线程池的简单案例

上代码:

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

【java】scala ExecutorService停止线程池的简单案例

推荐文章

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧