我有使用jmx运行某项工作的简单课程。我想实现启动和停止这项工作的功能(它可能会运行很长时间)。像这样:
sess.run()
没有想法如何让它发挥作用。如何使这些方法在并行流中独立运行,并使方法stop()影响start()内的循环。
答案 0 :(得分:0)
一些建议:
简单示例:
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;
@Component
@ManagedResource
public class JobRunner
{
private final AtomicBoolean stopped = new AtomicBoolean(true);
private Thread jobThread = null;
@ManagedOperation
public void start() {
if(stopped.compareAndSet(false, true)) {
jobThread = new Thread("JobThread") {
public void run() {
while(!stopped.get()) {
// Some actions..
// Occassionally pause so the job can be interrupted
try {
Thread.currentThread().join(100);
} catch (InterruptedException iex) {
if(!stopped.get()) {
System.err.println("Job Thread was interrupted but not stopped");
JobRunner.this.stop();
break;
}
}
}
}
};
jobThread.setDaemon(true); // Optional
jobThread.start();
} else {
throw new IllegalStateException("Job was already running");
}
}
@ManagedOperation
public void stop() {
if(stopped.compareAndSet(true, false)) {
jobThread.interrupt();
jobThread = null;
} else {
throw new IllegalStateException("Job was not running");
}
}
}