可能重复:
启动/挂起/恢复/挂起…由其他类调用的方法
我想实现一个Anytime k-NN分类器,但我找不到一种方法来在特定的时间量内调用"分类(…)"方法,挂起它,在方法挂起之前获得可用结果,在特定时间量内恢复方法,挂起来它,在方法挂起之前获取可用结果,等等…
提前感谢!
我最近在这里发布了一个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();
}