简体   繁体   English

停止线程并释放Java中的锁

[英]Stop a thread and release the lock in Java

I have a ServerState object: 我有一个ServerState对象:

public class ServerState {
    public static final LOCK = new ReentrantLock();
    public static Map<String, Object> states = new HashMap<>();
}

Thread A: 线程A:

public class ThreadA extends Thread {
    @Override
    public void run() {
        ServerState.LOCK.lock();
        // do some dirty work
        ServerState.LOCK.unlock();
    }
}

My question is: when thread A has acquired the lock and is doing some dirty work, thread B wants to terminate A immediately but want it release the lock before its terminate, how can I achieve this? 我的问题是:当线程A获得了该锁并进行了一些肮脏的工作时,线程B要立即终止A,但又希望它在终止之前释放该锁,我该如何实现? I am not looking for use a flag to indicate whether the thread is terminated like this: 我不是在寻找使用标志来指示线程是否像这样终止:

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();
        }
}

What I want to achieve is to terminate the thread and release the lock WITHOUT proceeding to the next iteration. 我要实现的是终止线程并释放锁,而无需进行下一个迭代。 Is is possible to do it in Java? 用Java可以做到吗?

You can use thread interruption mechanism . 您可以使用线程中断机制 If you want to interrupt on LOCK acquiring, you should use LOCK.lockInterruptibly() instead of LOCK.lock() : 如果要在获取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()
    }
  }
};

Then, to stop thread1 just call 然后,要停止thread1只需调用

thread1.interrupt();

from another thread. 从另一个线程。

Also I'd suggest to move actual logic from Thread to Runnable : 我也建议将实际逻辑从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM