June 2018 Update
This commit is contained in:
parent
ba8067c3b7
commit
22f33d4004
5278 changed files with 84726 additions and 14379 deletions
20
Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin
Normal file
20
Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
// version 1.1.51
|
||||
|
||||
import java.util.concurrent.Semaphore
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val numPermits = 4
|
||||
val numThreads = 9
|
||||
val semaphore = Semaphore(numPermits)
|
||||
for (i in 1..numThreads) {
|
||||
thread {
|
||||
val name = "Unit #$i"
|
||||
semaphore.acquire()
|
||||
println("$name has acquired the semaphore")
|
||||
Thread.sleep(2000)
|
||||
semaphore.release()
|
||||
println("$name has released the semaphore")
|
||||
}
|
||||
}
|
||||
}
|
||||
30
Task/Metered-concurrency/Scala/metered-concurrency.scala
Normal file
30
Task/Metered-concurrency/Scala/metered-concurrency.scala
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
class CountingSemaphore(var maxCount: Int) {
|
||||
private var lockCount = 0
|
||||
|
||||
def acquire(): Unit = {
|
||||
while ( {
|
||||
lockCount >= maxCount
|
||||
}) wait()
|
||||
lockCount += 1
|
||||
}
|
||||
|
||||
def release(): Unit = {
|
||||
if (lockCount > 0) {
|
||||
lockCount -= 1
|
||||
notifyAll()
|
||||
}
|
||||
}
|
||||
|
||||
def getCount: Int = lockCount
|
||||
}
|
||||
|
||||
object Worker {
|
||||
def main(args: Array[String]): Unit = {
|
||||
val (lock, crew) = (new CountingSemaphore(3), new Array[Worker](5))
|
||||
|
||||
for { i <- 0 until 5} {
|
||||
crew(i) = new Worker(lock, i)
|
||||
crew(i).start()
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue