2020-04-08(1114. 按序打印*)

难度 简单
低速通过,涉及线程的还不是很熟,后面需要系统看下线程的。
执行用时 :18 ms, 在所有 Java 提交中击败了6.70%的用户
内存消耗 :39.1 MB, 在所有 Java 提交中击败了5.09%的用户

int mark = 0;
    Object lock = new Object();
    public Foo() {
    }

    public void first(Runnable printFirst) throws InterruptedException {
        synchronized(lock){
            // printFirst.run() outputs "first". Do not change or remove this line.
            printFirst.run();
            mark = 1;
            lock.notifyAll();
        }
    }

    public void second(Runnable printSecond) throws InterruptedException {
        synchronized(lock){
            while(mark != 1){
                lock.wait();
            }
            // printSecond.run() outputs "second". Do not change or remove this line.
            printSecond.run();
            mark = 2;
            lock.notifyAll();
        }

    }

    public void third(Runnable printThird) throws InterruptedException {
        synchronized(lock){
            while(mark != 2){   
                lock.wait();
            }
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
            lock.notifyAll();
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容