具有N个线程的多线程

时间:2013-10-11 18:29:25

标签: java multithreading

我正在尝试解决一个问题,无论这是否可行,或者是否试图与本论坛的专家一起理解,问题在于使用java进行线程间通信。

我有一个班级:

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

我有4个或更多线程,例如:

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

我必须以这种方式设计同步,如果一个线程正在设置一个方法,所有其他线程将在其他方法上运行

e.g:

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()

2 个答案:

答案 0 :(得分:9)

您必须在外部执行此操作。

Runnable个实例之间共享ReentrantLock

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 
}

相应处理Exception个。当tryLock()运行时,它返回

  

如果锁是空闲的并且被当前线程获取,则为true,或者   当前线程已经锁定了锁;否则

立即返回,不涉及阻止。如果它返回false,则可以使用其他方法。完成对setX()的操作后,您不会忘记释放锁。

答案 1 :(得分:3)

好问题。 您可以使用tryLock

您应该执行以下操作:

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

   }
   public void setY() {
        // Your stuff here
   }
}
相关问题