Mutilthreading with N Threads

I am trying to solve a problem, whether it can be feasible or not trying to understand with experts there, in this forum, the problem is cross-thread communication using java.

I have a class:

class A {
    public void setX() {}
    public void setY() {}
}

I have 4 or more threads, for example:

T1,T2,T3,T4 are the threads that operates on this Class

I need to construct synchronization in this way, if at any time, if a thread sets up one method, all other threads will work with another method.

eg:.

if thread T1 is operating on setX() methods then T2,T3,T4 can work on setY()
if thread T2 is operating on setX() methods then T1,T3,T4 can work on setY()
if thread T3 is operating on setX() methods then T1,T2,T4 can work on setY()
if thread T4 is operating on setX() methods then T1,T2,T3 can work on setY()
+4
source share
2 answers

You will have to do it from the outside.

Share ReentrantLockbetween instances Runnable.

A a = new A();
ReentrantLock lock = new ReentrantLock();
...
// in each run() 
if (lock.tryLock()) {
    try {
        a.setX(); // might require further synchronization
    } finally {
        lock.unlock();
    }
} else {
    a.setY(); // might require further synchronization 
}

Handle Exceptionaccordingly. When tryLock()launched, it returns

true, , ; false

, . false, . setX().

+9

. tryLock.

- :

class A
{
   public void setX() {
        if (tryLock(m_lock))
        {
           // Your stuff here
        } else {
           setY();
        }

   }
   public void setY() {
        // Your stuff here
   }
}
+3

All Articles