重构同步机制以不使用线程实例作为监视器

时间:2019-05-14 10:35:21

标签: java multithreading sonarqube sonarqube-scan

我有一个遗留应用程序,该应用程序最近已与SonarQube集成在一起。这行this.notify();同步方法中显示的错误显示为“重构同步机制以不将线程实例用作监视器”(方法“ wait(...)”,“ notify()”和“ notifyAll()”不应为在线程实例上调用)。我是多线程的初学者。谁能指出如何解决此问题?下面是代码片段

public synchronized void shutdown() {
        bShutdown = true;
        log.info("Shutting down Cleaner.");
        this.interrupt();
        try {
            this.wait(5000); // This line is causing sonar issue.
        } catch (InterruptedException ex) {
            log.warn("Cleaner shutdown notification received.");
            log.debug("Shutdown wait interrupted.", ex);
        }
        log.info("Cleaner shutdown ready.");
    }

我还有一个重写的run()方法,看起来像这样

public void run() {
        log.debug("Cleaner thread started.");
        bShutdown = false;
        while (!bShutdown) {
            try {
                onWakeUp();
                Thread.sleep(frequency * FREQUENCY_TO_MSEC_MULTIPLIER);
            } catch (InterruptedException ex) {
                log.debug("Cleaner thread Interrupted (probably for shutdown sequence)", ex);`enter code here`
            }
        }

        this.notifyShutdownReady();
    }

onWakeUp() method has some cleanup code

public synchronized void notifyShutdownReady() {
    this.notify();
}

0 个答案:

没有答案