2

我有“创建者”类,它具有创建线程的匿名内部可运行类。我也有创建 GUI 的 GUI 类,按下按钮执行“创建者”类。但随后我的 GUI 冻结,直到“创建者”创建的所有线程都完成。我发现 SwingWorker 在这种情况下可以帮助我,但我不明白如何在这种特殊情况下创建一个。除了 SwingWorker,还有其他简单的方法吗?

这是我的 Creator 类的代码:

public class Creator {

    final ExecutorService es;
    Collection<Future<?>> futures = new LinkedList<>();


    public Creator() {
        es = Executors.newFixedThreadPool(10);
    }

    public void runCreator() {

        for (int i = 0; i < 100; i++) {
            futures.add(es.submit(new Check(i)));
        }

        es.shutdown();

        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (Exception ex) {

            }
        }

    }

    private class Check implements Runnable {

    private int i;

        private Check(int i) {
            this.i = i;

        }

        @Override
        public void run() {

    System.out.println("Number: "+i);

    try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {

            }
        }
    }
}
4

2 回答 2

0

The reason why your code is hanging until it completes, is because of the call to your Future's get method. This will wait until it has completed. Also, you probably do not want to shutdown your pool right after adding all of your threads. It would be better to just add a on close event and shut it down there.

Since all that you are doing is printing a number and sleeping, you do not need to wait for the Future to complete. Just remove the call to get and the delay should stop.

于 2012-07-24T20:24:48.167 回答
0

是的,Swing 工作者是要走的路——网上有足够多的例子,但总结一下——doInBackground()如果你想报告临时进度,请使用publish()/process()并最终将你的数据获取到 Swing EDT 线程在done().

PS。与 SwingWorker 的使用无关,您可能需要考虑使用完成服务,而不是按顺序等待所有期货。

于 2012-07-25T00:40:24.840 回答