我有一个ServerState
对象:
public class ServerState {
public static final LOCK = new ReentrantLock();
public static Map<String, Object> states = new HashMap<>();
}
线程A:
public class ThreadA extends Thread {
@Override
public void run() {
ServerState.LOCK.lock();
// do some dirty work
ServerState.LOCK.unlock();
}
}
我的问题是:当线程A获得了该锁并进行了一些肮脏的工作时,线程B想要立即终止A,但又希望它在终止之前释放该锁,我该如何实现?我不是在寻找使用标志来指示线程是否像这样终止:
public class ThreadA extends Thread {
volatile boolean isFinished = false;
@Override
public void run() {
while (!isFinished) {
ServerState.LOCK.lock();
// do some dirty work
ServerState.LOCK.unlock();
}
}
我想要实现的是终止线程并释放锁,而无需进行下一个迭代。用Java可以做到吗?
答案 0 :(得分:1)
您可以使用线程interruption mechanism。
如果您想中断LOCK
的获取,则应使用LOCK.lockInterruptibly()
而不是LOCK.lock()
:
Thread thread1 = new Thread() {
@Override
void run() {
try {
LOCK.lockInterruptibly();
System.out.println("work");
LOCK.unlock();
} catch (InterruptedException ier) {
this.interrupt()
}
}
};
然后,要停止thread1
,只需致电
thread1.interrupt();
来自另一个线程。
我也建议将实际逻辑从Thread
移至Runnable
:
Thread thread1 = new Thread(
new Runnable() {
@Override
void run() {
try {
LOCK.lockInterruptibly();
System.out.println("work");
LOCK.unlock();
} catch (InterruptedException ier) {
Thread.currentThread().interrupt()
}
}
}
);