Java threads: wait and notify methods

后端 未结 7 1586
遥遥无期
遥遥无期 2020-12-04 00:28

I have a thread that calls the wait method and can only be awoken when the notify method called from some other class:

 class Threa         


        
7条回答
  •  失恋的感觉
    2020-12-04 00:34

    1) You need to add some flag that is used to communicate between the threads, so that B can signal to A when it is finished. A simple boolean variable is fine, as long as it is only read and written within the synchronized blocks.

    synchronized(this) {
        for(int i=0;i<100;i++) {
            total += i;
        }
        isDone = true;
        notify();
    }
    

    2) A needs to loop while waiting. So if your boolean variable was called isDone, and was set to true by threadB, then threadA should have some code like this:

    synchronized(b) {
        System.out.println("Waiting for b to complete...");
        while( ! isDone ) b.wait();
    }
    

    In this particular case, there's actually no reason to have the synchronized block in A - since threadB doesn't do anything after it finishes running, and A doesn't do anything except wait for B, threadA could simply call b.join() to block until it finishes. I assume that your actual use case is more complex than this.

提交回复
热议问题