Created
August 1, 2013 04:59
-
-
Save patorash/6128517 to your computer and use it in GitHub Desktop.
Javaの本を見ながらKotlinでThreadでの排他制御の練習をしていたやつ。
This file contains hidden or 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
package com.rhizome.KotlinThreadChallenge | |
import kotlin.concurrent.thread | |
import java.util.concurrent.locks.Lock | |
import java.util.concurrent.locks.ReentrantLock | |
import kotlin.concurrent.withLock | |
fun main(args: Array<String>) { | |
val bottle = Bottle() | |
val yield = { | |
while (bottle.drink(200)) { | |
println(Thread.currentThread().getName() + " did drink water") | |
Thread.sleep(200) | |
} | |
} | |
val yamada = thread(name="yamada", block=yield) | |
val tanaka = thread(name="tanaka", block=yield) | |
yamada.join() | |
tanaka.join() | |
println("water: " + bottle.water) | |
} | |
class Bottle { | |
var water = 1000 | |
class object { | |
val lock = ReentrantLock() | |
} | |
private fun contains(amount : Int) : Boolean = amount <= water | |
public fun drink(amount : Int) : Boolean { | |
return lock.withLock { | |
if (contains(amount)) { | |
println("before water: " + water) | |
water -= amount | |
println("after water: " + water) | |
true | |
} else { | |
false | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment