上代码:
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方法详解