力扣上的一道题,三个线程按照顺序分别打印出来one、tow、three:

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
47
48
49
50
class Foot {
private val flag:AtomicInteger = AtomicInteger(0)
@Throws(InterruptedException::class)
fun first(printFirst: Runnable) {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run()
flag.incrementAndGet()
}

@Throws(InterruptedException::class)
fun second(printSecond: Runnable) {
while (flag.get() != 1) {
}
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run()
flag.incrementAndGet()
}

@Throws(InterruptedException::class)
fun third(printThird: Runnable) {
while (flag.get() != 2) {
}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run()
flag.incrementAndGet()
}

internal class PrintRunnable(private val text: String) : Runnable {
override fun run() {
println(text)
}

}

}
fun main(){
val foot = Foot()
thread {
val tow = Foot.PrintRunnable("tow")
foot.second(tow)
}
thread {
val three = Foot.PrintRunnable("three")
foot.third(three)
}
thread {
val one = Foot.PrintRunnable("one")
foot.first(one)
}
}