Conditional code synchronization for specific threads only

Suppose there are three groups of threads. let's say A, B and C.

I want to create a block of code in a method that blocks happening between threads of type A and B, threads C are allowed in all cases of a method call, including the blocking part.

In other words, if stream type A is in the blocked part of the code, B is blocked, but C is not blocked.

Do you have any idea if this can be done? If so, how can this be done?

+4
source share
2 answers

You may have helper lock methods:

private final ReentrantLock mLock = new ReentrantLock();

void conditionalLock() {
    ThreadGroup group = Thread.currentThread().getThreadGroup();
    if (group.equals(groupA) || group.equals(groupB)) {
        mLock.lock();
    }
}

Change the changed / simplified state as suggested by erickson

void conditionalUnlock() {
    if (mLock.isHeldByCurrentThread()) {
        mLock.unlock();
    }
}

:

    conditionalLock();
    try {
        // block you want to synchronize between threads of group A & B
    } finally {
        conditionalUnlock();
    }
+4

, , .

Your Threads if, ( Thread).

if (Thread.currentThread().getName().contains("A") || Thread.currentThread().getName().contains("B")){
    synchronized(this){
        //do stuff
    }
}else{
    //do stuff or even check if its type C
}
+1

All Articles