多线程按顺序打印数字

多线程按顺序打印数字:

示例结题如下:

A线程打印:1

B线程打印:2

C线程打印:3

A线程打印:4

B线程打印:5

C线程打印:6

.........

怎样高效率实现?

package com.youzu.got.world

import com.google.common.base.Stopwatch
import java.util.concurrent.CountDownLatch

@Volatile
var runNum = 0
var threadNum = 3
var maxNum = 300_000_000


class MyThread(private val threadName: String, var curNum: Int, private val latch: CountDownLatch) : Thread() {

  override fun run() {

    while (true) {
      if (curNum <= runNum) {
        if (runNum >= maxNum) {
          break
        }
        //println("$threadName : ${runNum + 1}")
        curNum += threadNum
        runNum++
      }
      if (runNum >= maxNum) {
        break
      }
    }
    latch.countDown()
    println("$threadName stop")
  }
}

fun main() {

  var watch = Stopwatch.createStarted()
  val latch = CountDownLatch(threadNum)
  for (n in 0 until threadNum) {
    MyThread("threadName_$n", n, latch).start()
  }
  latch.await()
  watch.stop()
  println("cost: ${watch}")

}

 

 

 

无锁方式实现

posted @ 2021-08-16 11:57  itank  阅读(345)  评论(0编辑  收藏  举报