Kotlin同步无法正常工作

时间:2018-12-11 01:42:41

标签: kotlin synchronized

我正在尝试创建一个简单的程序,该程序是使用并发(杂质在单元格中左右随机移动)的布朗运动模型。我有杂质和细胞类。电池类别包含电池阵列,这表示目前每个电池中有多少杂质。每个杂质对象都会在自己的线程中更改单元格中的单元格数组。我正在启动线程,并且它们在无限循环中运行1秒钟。但是在此之前和之后,我打印了单元格中的杂质总和,这些值不相等,这意味着我在同步方面做错了。这是代码:

Cells类:

object Cells {
    var cell = Array(N) { 0 }

    fun addImpurity(impurity: Impurity) {
        cell[impurity.currentCell]++
    }

    @Synchronized
    fun move(impurity: Impurity, direction: Direction) {
            if (direction == Direction.LEFT && impurity.currentCell > 0) {
                cell[impurity.currentCell]--
                cell[impurity.currentCell - 1]++

                impurity.currentCell--
            } else if (direction == Direction.RIGHT && impurity.currentCell < N - 1) {
                cell[impurity.currentCell]--
                cell[impurity.currentCell + 1]++

                impurity.currentCell++
            }
            Unit
    }

    fun printCells() {
        for (c in cell)
            print("$c ")
    }
}

enum class Direction {
    LEFT, RIGHT
}

杂质等级:

class Impurity(var currentCell: Int) {
    private lateinit var thread: Thread

    init {
        Cells.addImpurity(this)
    }

    fun startMoving() {
        thread = Thread {
            while (true) {
                if (random() > P)
                    Cells.move(this, Direction.RIGHT)
                else
                    Cells.move(this, Direction.LEFT)
            }
        }

        thread.start()

    }

    fun stopMoving() = thread.interrupt()
}

和主要:

const val N = 10
const val K = 15
const val P = 0.5

fun main(args: Array<String>) {
    val impurities = ArrayList<Impurity>()

    for (i in 1..K)
        impurities.add(Impurity(0))

    println(Cells.cell.sum())

    startMoving(impurities)

    Thread.sleep(1000)

    stopMoving(impurities)

    Cells.printCells()

    println(Cells.cell.sum())
}

private fun startMoving(impurities: ArrayList<Impurity>) {
    for (impurity in impurities)
        impurity.startMoving()
}

private fun stopMoving(impurities: ArrayList<Impurity>) {
    for (impurity in impurities)
        impurity.stopMoving()
}

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为最好手动通知线程它应该完成工作,方法是让线程包含它所引用的一些标志,以便知道何时退出循环。例如:

class Impurity(var currentCell: Int) {
    ...
    private var _continue = true

    fun startMoving() {
        thread = Thread {
            while (_continue) {
        }
    }

    ...

    fun stopMoving() {
        _continue = false
    }
}

此外,您可能还想等到实际线程本身死掉,作为对stopMoving的调用的一部分。这将确保在调用Cells.printCells之前,所有线程都确实接收到该信号并退出其循环。例如,您可以将此方法添加到Impurity类中:

fun waitForEnded() = thread.join()

在向每个线程发出停止信号后,您可以更新主类中的stopMoving来调用此方法:

private fun stopMoving(impurities: ArrayList<Impurity>) {
    for (impurity in impurities)
        impurity.stopMoving()
    impurities.forEach(Impurity::waitForEnded)
}