zoukankan      html  css  js  c++  java
  • 关于Leetcode的交替打印FooBar,我的答案一直超时

    class FooBar {
        private int n;
    
        public FooBar(int n) {
            this.n = n;
        }
    
        private volatile boolean fooStarted;
        private final Object lock = new Object();
        public void foo(Runnable printFoo) throws InterruptedException {
    
            for (int i = 0; i < n; i++) {
                System.out.println("foo " + i);
                synchronized (lock) {
                    System.out.println("foo synchronized" + i);
                    // printFoo.run() outputs "foo". Do not change or remove this line.
                    fooStarted=true;
                    printFoo.run();
                    lock.notifyAll();
                    System.out.println("end notify");
                    lock.wait();
                    System.out.println("end wait");
                    System.out.println("aa");
                }
            }
        }
    
        public void bar(Runnable printBar) throws InterruptedException {
    
            for (int i = 0; i < n; i++) {
                System.out.println("bar " + i);
                synchronized (lock) {
                    System.out.println("bar synchronized" + i);
                    if (!fooStarted) {
                        System.out.println("prepare wait");
                        lock.wait();
                        System.out.println("begin wait");
                    }
                    // printBar.run() outputs "bar". Do not change or remove this line.
                    printBar.run();
                    lock.notifyAll();
                    System.out.println("bar notify");
    /*
                    if (i==n-1) {
                        break;
                    }
    */
                    lock.wait();
    
                    System.out.println("bar wait");
                }
            }
        }
    }

    起始是因为bar的wait调用之后,这个bar线程一直存活,导致该线程无法结束,引起的Leetcode判定超时。

    只需要加上那个if break的代码就行了。

    另说一句:这里我对bar的最开始用的是if判定的wait,而不是用while判定的wait,因为我认为没有必要哈。

  • 相关阅读:
    SpringBoog三步实现热部署
    Postman文档Using cookies及其实践
    <packaging>war</packaging>有毛用?
    vm win7镜像
    HttpClient发起请求,将响应结果(header和entity)设置到response中返回
    文件上传inputstream转为multipartfile
    前后端分离文件下载接口定义
    "随机数不随机"???
    Lombok注解-@SneakyThrows
    一文解读数据湖(转)
  • 原文地址:https://www.cnblogs.com/woyujiezhen/p/14494096.html
Copyright © 2011-2022 走看看