Stopper的使用
工具类,抽象死循环逻辑的
import java.util.concurrent.atomic.AtomicBoolean;
/**
* if the process closes, a signal is placed as true, and all threads get this flag to stop working
*/
public class Stopper {
private static AtomicBoolean signal = new AtomicBoolean(false);
public static final boolean isStopped(){
return signal.get();
}
public static final boolean isRunning(){
return !signal.get();
}
public static final void stop(){
signal.set(true);
}
}
使用
while (Stopper.isRunning()) {
InterProcessMutex mutex = null;
try {
if (zkClient.getZkClient().getState() == CuratorFrameworkState.STARTED) {
mutex = zkClient.blockAcquireMutex();
// zk获取到锁开始执行业务逻辑,此处可以使用Thread.yield代理Thread.sleep方法
}
} catch (Exception ex) {
logger.error("master scheduler thread error", ex);
} finally {
zkClient.releaseMutex(mutex);
}
}
原创:做时间的朋友