Created
May 11, 2020 22:16
-
-
Save radityagumay/7f2a23cda055d85e46d4a178b65851f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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