[英]Stop a thread and release the lock in Java
我有一個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可以做到嗎?
您可以使用線程中斷機制 。 如果要在獲取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()
}
}
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.