How to make another thread sleep in Java

前端 未结 3 1577
无人共我
无人共我 2020-11-30 12:59

I have a class that extends Thread. This thread when running spends most of it\'s time sleeping, it will perform a check, if true perform a simple action, then sleep for 1/2

3条回答
  •  独厮守ぢ
    2020-11-30 13:41

    Add this to your thread:

    public AtomicBoolean waitLonger = new AtomicBoolean  ();
    public Object lock = new Object ();
    

    In run():

    synchronized (lock) {
        if (waitLonger.get ()) {
            lock.wait ();
        }
    }
    

    In the other thread:

    synchronized (lock) {
    try {
        sleeper.waitLonger.set(true);
        ...
        lock.notify();
        sleeper.waitLonger.set(false);
    }
    

    This way, you can make the sleeper wait until the other work has completed.

提交回复
热议问题