package johnnyLearning import java.lang.Exception /** * two thread to print odd and even number * */ class solution { val lock = java.lang.Object() val num = 0 fun printTwoNumber() { val thread1 = PrintThread(num, true, lock) val thread2 = PrintThread(num, false, lock) thread1.start() thread2.start() } class PrintThread public constructor(num_: Int, showOdd_: Boolean, lock_: java.lang.Object) : Thread() { var num = num_ val showOdd = showOdd_ val lock = lock_ override fun run() { super.run() while (true) { synchronized(lock) { when (showOdd) { true -> { if (num % 2 == 0) { lock.notify()//get lock before print println("odd: $num") lock.wait()//hand over lock after print } } false -> { if (num % 2 != 0) { lock.notify() println("even: $num") lock.wait() } } }//end when } num++ try { if (num > 30) { break; } } catch (e: Exception) { e.printStackTrace() } }//end while println("thread stop") } } }
测试:
val solution = johnnyLearning.solution()
solution.printTwoNumber()
输出:
odd: 0 even: 1 odd: 2 even: 3 odd: 4 even: 5 odd: 6 even: 7 odd: 8 even: 9 odd: 10 even: 11 odd: 12 even: 13 odd: 14 even: 15 odd: 16 even: 17 odd: 18 even: 19 odd: 20 even: 21 odd: 22 even: 23 odd: 24 even: 25 odd: 26 even: 27 odd: 28 even: 29 odd: 30 thread stop