未来的结果一旦到达就更新UI

时间:2012-12-05 14:27:25

标签: java future

JList使用DefaultListModel来更新UI中列表中的字符串,如图所示返回

class ResponseGiver implements Callable<Future>{

        int i;

       //Constructor to initialize i

     String call(){
      ...............
      ...............
      return i;
  }

我还有其他课程将更新从上面获得的结果

class Viewer {

    ExecutorService es = new Executors.newFixedThreadPool(10);
    List<Future<String>> futures = new ArrayList<Future<String>>();
    for(int i =0;i<10;i++)
      {
         futures.add(new ResponseGiver(i));
      }
 for(Future<String> x : futures)  //loop 2nd will be called 10 times
  {
     String p = x.get(); 
       //update GUI with p
   }

现在的问题是,假设在循环2中,在第5个循环中,get()函数花费一些时间说10秒,并且在平均时间内,从第6到第10的其他期货已经准备好了结果。 所以我的屏幕会等待第5个结果,即使是第6到第10个也准备好了。 我希望一旦10个期货中的任何一个返回结果,我的屏幕就会更新。

2 个答案:

答案 0 :(得分:1)

使用标准API,您可以使用ExecutorCompletionService。它允许提交Callable个实例并返回Future个对象,就像普通的ExecutorService一样。但它还允许按照完成顺序获取Future个对象:使用ExecutorCompletionService#take()方法。此方法将阻止,直到有新的Future可用。您可以将此视为Futures被置于阻塞队列中。

您可以从完成服务启动一个使用这些Future对象的线程。然后可以使用这种Future的结果来更新GUI。 (请注意,此更新必须使用SwingUtilities.invokeLater再次在事件调度线程上完成。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class ExecutorCompletionServiceTest
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.getContentPane().setLayout(new BorderLayout());

        JButton button = new JButton("Run");
        f.getContentPane().add(button, BorderLayout.NORTH);

        final DefaultListModel<String> listModel = new DefaultListModel<String>();
        JList<String> list = new JList<String>(listModel);
        f.getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);

        final Callback callback = new Callback()
        {
            @Override
            public void call(final String result)
            {
                SwingUtilities.invokeLater(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        listModel.addElement(result);
                    }
                });
            }
        };

        button.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                createTasks(callback);
            }
        });

        f.setSize(300, 300);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    interface Callback
    {
        void call(String result);
    }


    private static Random random = new Random(0);

    static class ResponseGiver implements Callable<String>
    {
        private int i;

        ResponseGiver(int i)
        {
            this.i = i;
        }

        @Override
        public String call()
        {
            int delayMS = 250 + random.nextInt(500);

            // Simulate a longer delay for task 5
            if (i == 5)
            {
                delayMS += 3000;
            }
            try
            {
                System.out.println("For "+i+" waiting "+delayMS+" ms");
                Thread.sleep(delayMS);
                System.out.println("For "+i+" waiting "+delayMS+" ms DONE");
            }
            catch (InterruptedException e)
            {
                Thread.currentThread().interrupt();
            }
            return String.valueOf(i);
        }
    }

    private static void createTasks(final Callback callback)
    {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        final CompletionService<String> executorCompletionService =
            new ExecutorCompletionService<String>(executorService);
        final int n = 10;
        for (int i = 0; i < 10; i++)
        {
            executorCompletionService.submit(new ResponseGiver(i));
        }
        Thread thread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                processResults(executorCompletionService, n, callback);
            }
        });
        thread.start();
    }

    private static void processResults(
        CompletionService<String> completionService, int n, Callback callback)
    {
        for (int i = 0; i < n; i++)
        {
            try
            {
                Future<String> future = completionService.take();
                String result = future.get();
                if (result != null)
                {
                    callback.call(result);
                }
                System.out.println("Processed "+(i+1)+" of "+n+" results");
            }
            catch (InterruptedException e)
            {
                Thread.currentThread().interrupt();
            }
            catch (ExecutionException e)
            {
                e.printStackTrace();
            }
        }
    }
}

答案 1 :(得分:0)

只需使用guava中的ListenableFuture即可。它更方便。