ReentrantLock和Condition的使用案例

186 阅读1分钟

使用重入锁ReentrantLock可以让线程按我们的规则执行,而非抢占式。以下例子是让我们的count为0的时候由加的线程一直加到10,在count为10的时候由减的线程一直减到0,两线程交替执行。犹如水池注满水又放干水,然后又注满水,是不是很无聊。

val lock : ReentrantLock = ReentrantLock(true)
lateinit var notEmpty: Condition
lateinit var notFull: Condition
var count = AtomicInteger(0)

fun main() {
    notEmpty = lock.newCondition()
    notFull = lock.newCondition()
    val t1 = Thread {
        lock.lockInterruptibly()
        try {
            while (count.get() >= 0) {
                if (count.get() == 0) {
                    notEmpty.await()
                }
                count.decrementAndGet()
                println("Thread-${Thread.currentThread().id}:" + count)
                if (count.get() < 10) {
                    notFull.signal()
                }
            }
        } finally {
            lock.unlock()
        }
    }
    t1.start()
    val t2 = Thread {
        lock.lockInterruptibly()
        try {
            while (count.get() <= 10) {
                if (count.get() == 10) {
                    notFull.await()
                }
                count.incrementAndGet()
                println("Thread-${Thread.currentThread().id}:"+count)
                if (count.get() > 0) {
                    notEmpty.signal()
                }
            }
        } finally {
            lock.unlock()
        }
    }
    t2.start()
}

以下为执行效果

image.png