Skip to content

Instantly share code, notes, and snippets.

@radityagumay
Created May 11, 2020 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radityagumay/7f2a23cda055d85e46d4a178b65851f8 to your computer and use it in GitHub Desktop.
Save radityagumay/7f2a23cda055d85e46d4a178b65851f8 to your computer and use it in GitHub Desktop.
fun main() {
val les = Executors.newFixedThreadPool(5)
for (i in 0..9) {
val worker: Runnable = WorkerThread("" + i)
les.execute(worker)
}
les.shutdown()
while (!les.isTerminated) { }
println("Finished all threads")
}
class WorkerThread(
private val command: String
) : Runnable {
override fun run() {
println(Thread.currentThread().name + " Start. Command = " + command)
processCommand()
println(Thread.currentThread().name + " End.")
}
private fun processCommand() {
try {
Thread.sleep(5000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
override fun toString(): String {
return command
}
}
// Log
/**
* pool-4-thread-1 Start. Command = 0
* pool-4-thread-4 Start. Command = 3
* pool-4-thread-3 Start. Command = 2
* pool-4-thread-2 Start. Command = 1
* pool-4-thread-5 Start. Command = 4
* pool-4-thread-1 End.
* pool-4-thread-3 End.
* pool-4-thread-3 Start. Command = 6. // this command process is waiting until pool-4-thread-3 is completed.
* pool-4-thread-4 End.
* pool-4-thread-5 End.
* pool-4-thread-1 Start. Command = 5
* pool-4-thread-2 End.
* pool-4-thread-5 Start. Command = 8
* pool-4-thread-4 Start. Command = 7
* pool-4-thread-2 Start. Command = 9
* pool-4-thread-5 End.
* pool-4-thread-2 End.
* pool-4-thread-4 End.
* pool-4-thread-3 End.
* pool-4-thread-1 End.
* Finished all threads
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment