1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock
private const val STATE_A = 1 private const val STATE_B = 2 private const val STATE_C = 3
@Volatile private var state = STATE_A
fun main() { val lock = ReentrantLock() val c1 = lock.newCondition() val c2 = lock.newCondition() val c3 = lock.newCondition() Thread { repeat(10) { lock.withLock { while (state != STATE_A) c1.await() println("A") state = STATE_B c2.signal() } } }.start() Thread { repeat(10) { lock.withLock { while (state != STATE_B) c2.await() println("B") state = STATE_C c3.signal() } } }.start() Thread { repeat(10) { lock.withLock { while (state != STATE_C) c3.await() println("C") state = STATE_A c1.signal() } } }.start() }
|