Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File
- import java.util.concurrent.locks.ReentrantLock
- import kotlin.concurrent.thread
- import kotlin.concurrent.withLock
- private fun <T : Number> T.fib(): Long {
- if (this.toLong() < 3) return 1
- var f = 1L
- var s = 1L
- val long = this.toLong()
- (3..long).forEach { _ ->
- val mem = s
- s += f
- f = mem
- }
- return s
- }
- fun main() {
- val lock = ReentrantLock()
- val noDataCondition = lock.newCondition()
- val container = ArrayDeque<String?>()
- val adder = thread {
- File("file.txt").forEachLine {
- lock.withLock {
- while (container.size >= 100)
- noDataCondition.await()
- container.add(it)
- noDataCondition.signalAll()
- }
- Thread.sleep(10)
- }
- lock.withLock(noDataCondition::signalAll)
- }
- (0..3).forEach { _ ->
- thread {
- while (adder.isAlive) {
- lock.withLock {
- while (container.isEmpty()) {
- if (!adder.isAlive) break
- noDataCondition.await()
- }
- if (!adder.isAlive) return@withLock
- println(container.removeFirst()!!.toLong().fib())
- noDataCondition.signal()
- }
- if (!adder.isAlive) break
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement