Frage

I have methodA and methodB and methodSync in my java program. I want that when a thread is inside methodSync other threads don't run the methodA and methodB and wait for methodSync to end. But methodA and methodB can run simultaneously.

If I want to sync 3 methods with each other I can use this code:

private static final Object LOCK = new Object();

public static void methodA() {
        synchronized (LOCK) {
                //Do Job
        }
}

public static void methodB() {
        synchronized (LOCK) {
                //Do Job
        }
}

public static void methodSync() {
        synchronized (LOCK) {
                //Do Job
        }
}

But this is not a solution for me because I want to run methodA and methodB simultaneously.

War es hilfreich?

Lösung

private static final Object A = new Object();
private static final Object B = new Object();

public static void methodA() {
    synchronized (A) {
            //Do Job
    }
}

public static void methodB() {
    synchronized (B) {
            //Do Job
    }
}

public static void methodSync() {
    synchronized (A) {
      synchronized (B) {
            //Do Job
      }
    }
}

I guess that will work. Good luck.

P.S. You can replace synchronized with ReadWriteLock (acquiring the read lock in methods A & B and the write lock in methodSync. If that's worth doing is if you want two callers in methodA at the same time.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top