LeetCode 按序打印

218 阅读1分钟

多线程按顺序执行,请看链接: LeetCode 按序打印

juc 下的工具类我就不用了,直接上最原始且基础的代码吧。写了半年 kotlin,真香

关键点

  • 将线程的执行串行化
  • Object#wait()的判断一定不能用 if,如果只执行一遍,那倒可以
  • Object#wait() 会释放锁,但是一定要先拿到锁(没有锁,何谈释放),所以配合 synchronized 使用
package com.example.starter

import kotlin.concurrent.thread

class Foo {
  @Volatile
  private var value = 1
  private val lock: Object = Object()

  @Throws(InterruptedException::class)
  fun first(printFirst: Runnable) {
    synchronized(lock) {
      while (value != 1) {
        lock.wait()
      }
      printFirst.run()
      value = 2
      lock.notifyAll()
    }
  }

  @Throws(InterruptedException::class)
  fun second(printSecond: Runnable) {
    synchronized(lock) {
      while (value != 2) {
        lock.wait()
      }
      printSecond.run()
      value = 3
      lock.notifyAll()
    }
  }

  @Throws(InterruptedException::class)
  fun third(printThird: Runnable) {
    synchronized(lock) {
      while (value != 3) {
        lock.wait()
      }
      printThird.run()
      value = 1
      lock.notifyAll()
      println()
    }
  }
}

fun main() {
  val foo = Foo()
  val first = Runnable { print(1) }
  val second = Runnable { print(2) }
  val third = Runnable { print(3) }
  thread {
    repeat(100) {
      foo.first(first)
    }
  }
  thread {
    repeat(100) {
      foo.second(second)
    }
  }
  thread {
    repeat(100) {
      foo.third(third)
    }
  }
}