简体   繁体   English

从ExecutorService更新JProgressBar

[英]Update JProgressBar from ExecutorService

I am pinging gateways using Java ICMP ping function. 我正在使用Java ICMP ping功能ping通网关。 To perform fast pinging I am using ExectorService which creates threads for pinging. 为了执行快速ping操作,我使用了ExectorService,它创建了用于ping的线程。 After address is pinged (or not) I want to update Jprogressbar after pinging. 在对地址执行ping操作后,我想在ping后更新Jprogressbar。 I have this code which is working but it updates Jprogressbar before job (ping thread) is finished. 我有此代码正在工作,但它会在作业(ping线程)完成之前更新Jprogressbar。 I want to update jprogressbar after job is finished. 我想在作业完成后更新jprogressbar。

private int NUM_THREADS = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
public void run() {
    int JProgressBarValue = 0;
    for (;GateWayKey<=GateWayKeyStop;GateWayKey++){
        ip="192.168."+GateWayKey+".1";
       exec.submit((new PingTask(ip,GateWayKey,true,scanFrameRefrence,ttl)));
       JProgressBarValue=(GateWayKey/GateWayKeyStop)*100;
       scanFrameRefrence.progressBar.setValue(JProgressBarValue);
       scanFrameRefrence.progressBar.repaint();
    }}

First of all, Swing components may not be used from outside of the event dispatch thread. 首先,不得在事件分发线程外部使用Swing组件。 So, the code updating the progress bar must be enclosed inside 因此,更新进度条的代码必须包含在其中

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        scanFrameRefrence.progressBar.setValue(value);
    }
});

Now, to answer the question. 现在,回答问题。 If you want to update the progress bar when a task finishes, the easier way is to have the task itself update the progress bar when at the end of its execution. 如果要在任务完成时更新进度条,则更简单的方法是让任务本身在执行结束时更新进度条。

Another way is to use an ExecutorCompletionService , which can be notified (thanks to a blocking queue) when each task has finished. 另一种方法是使用ExecutorCompletionService ,当每个任务完成时,可以将其通知(由于阻塞队列)。

Also, consider posting actual, compiling code, and respecting Java naming conventions: variables start with a lower-case letter. 另外,请考虑发布实际的编译代码,并遵守Java命名约定:变量以小写字母开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM