Eclipse 插件中,很多时候会遇到需要长时间执行的任务, 这些任务需要放在后台线程里运行, 否则,就会使 Eclipse 的 UI 僵住。 这个时候,我们需要使用 Eclipse 提供的 Job 或者 ProgressMonitorDialog 实现。
1. 使用 Job
Job job = new Job("Job") { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask("Start Task", 100); for (int i = 0; i < 100; i++) { if (monitor.isCanceled()) { break; } try { TimeUnit.MILLISECONDS.sleep(200L); } catch (InterruptedException e) { e.printStackTrace(); } monitor.subTask("Start sub task: " + i); monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }; job.schedule();
效果如下:
Job 是异步执行, 在 Job 执行的时候, Eclipse 的主界面还是可以进行其他操作的。
2. 使用 ProgressMonitorDialog
ProgressMonitorDialog dialog = new ProgressMonitorDialog(HandlerUtil.getActiveShell(event)); try { dialog.run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Start Task", 100); for (int i = 0; i < 100; i++) { if (monitor.isCanceled()) { break; } TimeUnit.MILLISECONDS.sleep(200L); monitor.subTask("Start sub task: " + i); monitor.worked(1); } monitor.done(); } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); }
效果如下:
ProgressMonitorDialog 是 modal 的对话框, 会 block 住 Eclipse 的主界面。