在Java中启动/挂起/恢复方法

时间:2012-07-21 12:52:49

标签: java multithreading java.util.concurrent concurrent-programming

  

可能重复:
  Start/Suspend/Resume/Suspend … a method invoked by other class

我想实现一个Anytime k-NN分类器,但我找不到一种方法来调用“classify(...)”方法一段特定的时间,暂停它,在方法暂停之前获取可用的结果,恢复方法一段特定的时间,暂停它,在方法暂停之前获得可用的结果,等等......

提前致谢!

1 个答案:

答案 0 :(得分:0)

我最近在这里发布了PauseableThread

您可以使用ReadWriteLock实现暂停。如果你每次有机会暂停时暂时抓住它上面的写锁定,那么你只需要一个暂停来抓住读锁来暂停你。

  // The lock.
  private final ReadWriteLock pause = new ReentrantReadWriteLock();

  // Block if pause has been called without a matching resume.
  private void blockIfPaused() throws InterruptedException {
    try {
      // Grab a write lock. Will block if a read lock has been taken.
      pause.writeLock().lockInterruptibly();
    } finally {
      // Release the lock immediately to avoid blocking when pause is called.
      pause.writeLock().unlock();
    }
  }

  // Pause the work. NB: MUST be balanced by a resume.
  public void pause() {
    // We can wait for a lock here.
    pause.readLock().lock();
  }

  // Resume the work. NB: MUST be balanced by a pause.
  public void resume() {
    // Release the lock.
    pause.readLock().unlock();
  }