我有两个单例对象的实例方法
method1
和 method2
。 method1
可以由单独的线程同时运行。这意味着我们可以有 5 个线程同时运行 method1
,或者 1 个线程同时运行 method2
。
我想在
method1
运行时阻止 method2
运行,并在 method2
运行时阻止 method1
运行。
我想过像下面的代码一样同步这两个方法,这解决了两个方法不能同时执行的问题,但它也会阻止我的5个线程同时运行
method1
,即使method2
是不运行。
void synchronized method1() {
//do something
}
void synchronized method2() {
//do other thing
}
第一次使用java多线程所以感谢一些建议,谢谢。
如果我处在你的位置,我会从定义一个接口开始:
interface ModeSwitch {
enum Mode {
NORMAL_MODE,
REFRESH_MODE
}
// Changes the switch mode to the `desiredMode` and locks it so that
// it cannot be changed by other threads.
//
// Waits for the lock count to become zero if the switch is not
// already set to the desired mode. Then, atomically changes the
// switch setting to the desired mode while incrementing the lock
// count before returning.
//
void lockTo(Mode desiredMode) throws InterruptedException;
// Decrements the lock count for the switch.
// Awakens other threads (if any) that are waiting to change the
// mode if the count reaches zero as a result.
//
void release();
}
我不认为我告诉你我将如何实现它真的符合这个网站的精神(请参阅我对你的问题的评论),但这里有一个提示:我会利用
ReentrantLock
对象,以及至少一个 Condition
对象,该对象将用于 signal()
-正在等待更改开关机会的线程。
额外加分:这样做的方式可以防止希望开关锁定在
NORMAL_MODE
中的线程从 挨饿 想要将开关锁定在 REFRESH_MODE
中的线程。