Last active
April 7, 2023 16:53
-
-
Save alifhasnain/2afd8c86e2bec31dae99578e6ade40a9 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
import java.util.concurrent.LinkedBlockingQueue | |
import java.util.concurrent.ThreadPoolExecutor | |
import java.util.concurrent.TimeUnit | |
import kotlin.random.Random.Default.nextInt | |
/* | |
* Here queue size is defined 3 | |
* so that means if the tasks in the queue exceeds 3 then the pool will create | |
* a new thread for the task execution. The pool can created maximum 5 threads in this case. | |
* If Queue size is less than or equal 3 then ThreadPool will use minimum number of threads | |
*/ | |
val pool = ThreadPoolExecutor( | |
/* corePoolSize = */ 1, | |
/* maximumPoolSize = */ 5, | |
/* keepAliveTime = */ 0, | |
/* unit = */ TimeUnit.MILLISECONDS, | |
/* workQueue = */ LinkedBlockingQueue<Runnable>(3) | |
) | |
fun main() { | |
printString() | |
} | |
fun printString() { | |
for (i in 1..8) { | |
pool.execute(getRunnable(i)) | |
if (i == 8) println("Called 8 Times") | |
} | |
} | |
private fun getRunnable(taskNo: Int): Runnable { | |
return Runnable { | |
val delay = nextInt(3,12).toLong() | |
println("Delaying $delay seconds for task no $taskNo") | |
TimeUnit.SECONDS.sleep(delay) | |
println("${Thread.currentThread().name} ------ Finished Task no: $taskNo") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment