Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*
- import java.util.*
- import java.util.concurrent.LinkedBlockingQueue
- private class ThreadPool<T>(
- threadsAmount: Int,
- action: (T) -> Unit
- ) : Closeable {
- private val actionThreads = Array(threadsAmount) {
- Thread {
- while (working || !taskQueue.isEmpty()) {
- val v = taskQueue.poll()
- if (v != null) action(v)
- }
- }
- }
- private val taskQueue: Queue<T> = LinkedBlockingQueue()
- @Volatile
- private var working = false
- fun start() {
- working = true
- actionThreads.forEach(Thread::start)
- }
- fun push(elem: T) = taskQueue.offer(elem)
- override fun close() {
- working = false
- }
- }
- private fun fib(number: Int): Int {
- if (number < 3)
- return 1
- var f = 1
- var s = 1
- (3..number).forEach { _ ->
- val mem = s
- s += f
- f = mem
- }
- return s
- }
- fun main() = System.`in`.bufferedReader().use { reader ->
- print("Threads amount: ")
- ThreadPool<Int>(reader.readLine().toInt()) { println(fib(it)) }.use { pool ->
- File("file.txt").bufferedReader().use { fileReader ->
- pool.start()
- fileReader.lines().forEach { pool.push(it.toInt()) }
- }
- }
- }
Add Comment
Please, Sign In to add comment