我在 eclipse 插件 Job
中运行一个执行长时间操作但没有太多输出的进程。
如果用户请求,我希望能够取消 Job
,但是通过下面的实现,Job
不会停止,除非进程将某些内容打印到输出流。
Process process = new ProcessBuilder(args).start();
Scanner scanner = new Scanner(
(new InputStreamReader(
process.getInputStream(), UTF_8_CHARSET)));
while (scanner.hasNext())
{
if (monitor.isCanceled() {
// user canceled the job, destroy the process to return
process.destroy();
break;
}
CONSOLE.getStream().println(scanner.nextLine());
}
try {
process.waitFor();
} catch (InterruptedException e) {
Activator.log(ERROR, e.getMessage(), e);
} finally {
process.destroyForcibly();
}
我是否有其他选项来处理作业的取消并更快地停止进程而不是等待新的换行?
最佳答案
您应该将读取进程输出流的代码放入一个单独的线程中,并在您的主循环中等待进程以短暂的超时结束,以便您可以检查是否已取消。
所以主要代码应该是这样的:
Process process = new ProcessBuilder(args).start();
// Read standard output
new StreamConsumer(process.getInputStream()).start();
// You should also always read stderr
new StreamConsumer(process.getErrorStream()).start();
// Wait for process to end and check for cancel
while (!process.waitFor(100, TimeUnit.MILLISECONDS) {
if (monitor.isCanceled() {
// user canceled the job, destroy the process to return
process.destroy();
break;
}
}
StreamConsumer
类似于:
public class StreamConsumer extends Thread
{
private final InputStream _input;
public StreamConsumer(final InputStream inputStream)
{
super();
_input = inputStream;
setDaemon(true);
}
@Override
public void run()
{
// TODO your code to read the stream
}
}
关于java - 取消 Eclipse 插件作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48986504/