我有一个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 实现吗?
最佳答案
您可以使用线程interruption mechanism 。
如果您想在 LOCK
获取时中断,则应使用 LOCK.lockInterruptically()
而不是 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()
}
}
}
);
关于java - Java中停止线程并释放锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51679921/