Search code examples
javajava-threads

How to handle two thread pause in a method


The situation is like this, methodB() is called again and again when the app is running. When methodC() is called, methodB() will pause until methodC() is done. When methodA() is called, it will pause until methodB() done for three times but skip "Code X".

I've tried to add locker2, lock2 and threadLocker2() to do the pause of methodA(), but it didn't work as methodB() also pause. Can anyone give me some suggestions how can I do this?

private final Object locker = new Object();
private boolean lock = false;

public void methodA() {
    //Lock until methodB() run three times

    //Do something
}

public void methodB() { //A thread called again and again
    //Do something

    threadLock();

    //Code X
}

public void methodC() {
    lock true;

    //Do something

    lock = false;
    synchronized (locker) { locker.notify(); }
}

private void threadLock() {
    synchronized (locker) {
        while (lock) {
            try {
                locker.wait();
            } catch (InterruptedException e) {}
        }
    }
}

Solution

  • I would use an atomic boolean (or integer) or a volatile boolean for that.

    This is the shared atomic / volatile boolean:

    private AtomicBoolean secondMethodIsDone = new AtomicBoolean(false);
    
    void firstMethod() {
       methodInOtherThread();
       while(!secondMethodIsDone.get()) {
            //thread sleep waiting...
       }
       // do your things when second is done     
    }
    

    This happens in another thread:

      void methodInOtherThread() {
          // do your stuff
          // whenever is done:
          secondMethodIsDone.set(true);
      }
    

    This should do it.