Consider a Swing application with a JList or JTable, when the selection changes a SwingWorker is started and loads related data from database and updates UI. 这工作正常,用户界面响应。
但是,如果用户正在快速更改所选行(按住键向上/向下键),我想确保最后选择的行是最后加载的行,而且我不想徒劳地查询数据库。所以我想要的是一个单线程执行器,它的后进先出队列大小=1。因此,向其提交任务会删除任何先前提交的任务,并使其一次最多执行 1 个任务,并且最多有 1 个任务等待执行。
我在 java.util.concurrent 中找不到类似的东西,所以我编写了自己的 Executor。我这样做是对的,还是我错过了并发包中的某些内容?解决方案是可以接受的还是有更好的方法来实现我想要的?
public class SingleLIFOExecutor implements Executor
{
private final ThreadPoolExecutor executor;
private Runnable lastCommand;
public SingleLIFOExecutor()
{
executor = new ThreadPoolExecutor(0, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
}
@Override
public void execute(Runnable command)
{
executor.remove(lastCommand);
lastCommand = command;
executor.execute(command);
}
}
这是一个示例,展示了如何使用它:
final Executor executor = new SingleLIFOExecutor();
JList jList = createMyList();
jList.addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
executor.execute(new MyWorker());
}
}
});