Using “notify()” & “wait()” instead of “suspend()” and “resume()” to control a thread

前端 未结 3 906
梦毁少年i
梦毁少年i 2021-01-06 16:29

I\'m trying to learn how to pause and resume a thread in java. I\'m using an Applet that implements Runnablehas 2 buttons \"Start\" and \"Stop\".

3条回答
  •  遥遥无期
    2021-01-06 17:16

    You can't just call notify and wait. You have to wait for something. And before calling notify, you have to make it so that there's nothing to wait for anymore.

    If your blocks aren't already synchronized, then something is wrong in your design.

    How can you call wait unless you have something to wait for? And how can you know that there is something to wait for if you haven't checked? And how can you check without synchronizing with the code that controls whether that thing has happened yet or not?

    How can you call notify unless something just happened that you need to notify the thread about? And how could something have happened that another thread cares about if you don't hold the lock that would tell that thread about it?

    You should use wait like this:

    while (something_to_wait_for()) wait();
    

    And that something_to_wait_for should check something that is protected by synchronization. And you can't make something_to_wait_for synchronized because then you have a race condition -- what if that something happens after something_to_wait_for returns but before you enter wait? Then you are waiting for something that already happened! So you need synchronization fundamentally. If you are just adding it at the end, your design is broken.

    The solution in your case is probably to add something to wait for. Perhaps a simple boolean variable is all you need. Then your code can be while (should_wait) wait();, should_wait = true;, and should_wait = false(); notifyAll(). You'll need synchronized to protect the boolean and the wait/notify logic.

提交回复
热议问题