1

可能重复:
开始/暂停/恢复/暂停……其他类调用的方法

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

提前致谢!

4

1 回答 1

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();
  }
于 2012-07-21T16:51:01.197 回答