fun test2() {
val countDownLatch = CountDownLatch(5)
val start = System.currentTimeMillis()
for (i in 0 until 5) {
val thread = Thread(Runnable {
Thread.sleep((i * 1000).toLong())
println("${Thread.currentThread().name}:执行结束")
countDownLatch.countDown()
})
thread.start()
}
//锁住主线程
countDownLatch.await()
println("所有线程结束")
val end = System.currentTimeMillis()
println((end - start) / 1000)
}
private fun test1() {
val newFixedThreadPool = Executors.newFixedThreadPool(5)
val start = System.currentTimeMillis()
for (i in 0 until 5) {
val runnable = Runnable {
Thread.sleep((i * 1000).toLong())
println("${Thread.currentThread().name}:执行结束")
}
newFixedThreadPool.submit(runnable)
}
newFixedThreadPool.shutdown()
while (true) {
if (newFixedThreadPool.isTerminated) {
println("所有线程结束")
break
}
}
val end = System.currentTimeMillis()
println((end - start) / 1000)
}
|