两个线程分别按顺序打印26个字母

2020-09-03  本文已影响0人  竖起大拇指

考察的主要是通知机制

1.使用对象wait和notify 相互通知

/**
 * Created by maozonghong
 * on 2020/9/3
 */
class LetterThread {

    companion object{
        var char:Char='A'
        private val lock = Object()
        class PrintLetter:Runnable{
            override fun run() {

                while (true){
                    synchronized(lock){
                        //notify并不释放锁,只是告诉调用过wait方法的线程可以去参与获得锁的竞争了,
                        // 但不是马上得到锁,因为锁还在自己手里,还没释放
                        lock.notify()
                        try {
                            Thread.sleep(1000)
                        }catch (e:Exception){
                            e.printStackTrace()
                        }

                        if(char.toInt()<91){
                            println(Thread.currentThread().name+"  "+ char.toString()+"  "+char.toInt())

                            char++

                            try {
                                //释放锁,让其他等待此锁的线程获取
                                lock.wait()
                            }catch (e:Exception){
                                e.printStackTrace()
                            }
                        }
                    }
                }

            }

        }

        @JvmStatic
        fun main(args: Array<String>) {
            var runnable=PrintLetter()
            Thread(runnable).start()
            Thread(runnable).start()
        }
    }
}

2.使用ReentrantLock

var reentrantLock=ReentrantLock(true)

        class LockPrintLetter:Runnable{
            override fun run() {

                while (true){

                    reentrantLock.lock()

                    try {
                        Thread.sleep(1000)

                        if(char.toInt()<91) {
                            println(Thread.currentThread().name + "  " + char.toString() + "  " + char.toInt())
                            char++
                        }
                    }finally {
                        reentrantLock.unlock()
                    }
                }
            }

        }

 @JvmStatic
        fun main(args: Array<String>) {
            var runnable=LockPrintLetter()
            Thread(runnable).start()
            Thread(runnable).start()
        }
    }

上一篇 下一篇

猜你喜欢

热点阅读