2013-10-11 78 views
4

我试图解决一个问题,这是否可行或不是试图了解与在这个论坛的专家,问题是与使用java的线程间通信。N线程多线程

我有一个类:

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

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

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

我要设计以这样的方式同步如果在任何时间,如果一个线程是设置一个方法,其他所有线程将在另一种方法操作

如:

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

你做了什么样的研究?你有什么尝试? – Gray

+0

我建议策略模式 – 2013-10-11 19:43:13

回答

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()运行它返回

真如果锁是免费的,是由当前线程获取,或者 锁已经被当前线程持有;否则为假

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

3

不错的问题。 您可以使用tryLock

你应该这样做:

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

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