簡體   English   中英

notifyAll()方法上的java.lang.IllegalMonitorStateException

[英]java.lang.IllegalMonitorStateException on notifyAll() method

在oracle網站的Java教程之后,我仍在學習Threads。

關於wait()和notifyAll(),我已經寫了一些代碼。 我的預期輸出是將run()中的消息打印10次,並在guardedJoy(GuardedBlock guardedBlock)方法中將“ joy”設置為false時,在guardedJoy(GuardedBlock guardedBlock)方法中顯示“ Fun stopFun StopFun Thread停止”消息。

這是我的代碼。

public class GuardedBlock {

private boolean joy = true;

public synchronized void guardedJoy(GuardedBlock guardedBlock) {

    System.out.println(Thread.currentThread().getName() + " Guard Joy method started");
    while (guardedBlock.joy) {
        try {
            System.out.println(Thread.currentThread().getName() + " Going to waiting state");
            guardedBlock.wait();
        } catch (InterruptedException ex) {
        }
    }
    System.out.println("Fun stopped by StopFun Thread");
}

private static class StopFun implements Runnable {

    private GuardedBlock guardedBlock;

    public StopFun(GuardedBlock guardedBlock) {
        this.guardedBlock = guardedBlock;
    }

    @Override
    public void run() {

        for (int x = 0; x < 100; x++) {
            try {
                Thread.sleep(500);
                System.out.println("Allowing fun since its only " + x + " times - " + Thread.currentThread().getName());

                if (x == 10) {
                    guardedBlock.joy = false;
                    guardedBlock.notifyAll();
                    break;
                }
            } catch (InterruptedException ex) {
            }
        }
    }
}

public static void main(String[] args) {

    GuardedBlock guardedBlock = new GuardedBlock();

    StopFun sf = new StopFun(guardedBlock);
    Thread stopFun = new Thread(sf);
    stopFun.start();

    guardedBlock.guardedJoy(guardedBlock);
    }
}

run方法中的代碼可以正常運行,但之后會引發類似這樣的異常。

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at Synchronization.GuardedBlock$StopFun.run(GuardedBlock.java:38)
    at java.lang.Thread.run(Thread.java:748)

我通過對夫婦的喜歡的網站的問題和答案去這個這個 ,但無法弄清楚究竟我做錯了。 幫助非常有價值。

謝謝。

必須在synchronized塊中調用wait()notify() / notifyAll()

synchronized (guardedBlock) {
    guardedBlock.notifyAll();
}

等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM