【发布时间】:2015-12-31 02:12:30
【问题描述】:
我知道这个问题已经回答了很多次,但我很难理解它是如何工作的。
所以在我的应用程序中,用户必须能够选择将添加到队列中的项目(使用ObservableList<Task> 显示在ListView 中),并且每个项目都需要由ExecutorService 按顺序处理。
此外,该队列应该是可编辑的(更改顺序并从列表中删除项目)。
private void handleItemClicked(MouseEvent event) {
if (event.getClickCount() == 2) {
File item = listView.getSelectionModel().getSelectedItem();
Task<Void> task = createTask(item);
facade.getTaskQueueList().add(task); // this list is bound to a ListView, where it can be edited
Future result = executor.submit(task);
// where executor is an ExecutorService of which type?
try {
result.get();
} catch (Exception e) {
// ...
}
}
}
用executor = Executors.newFixedThreadPool(1) 尝试过,但我无法控制队列。
我阅读了有关 ThreadPoolExecutor 和队列的信息,但我很难理解它,因为我对并发还很陌生。
我需要在后台线程中运行该方法handleItemClicked,以便 UI 不会冻结,我怎样才能做到最好?
总结:如何实现一个任务队列,可以编辑,并由后台线程按顺序处理?
请帮我解决
编辑
使用 vanOekel 的 SerialTaskQueue 类帮助了我,现在我想将任务列表绑定到我的 ListView。
ListProperty<Runnable> listProperty = new SimpleListProperty<>();
listProperty.set(taskQueue.getTaskList()); // getTaskList() returns the LinkedList from SerialTaskQueue
queueListView.itemsProperty().bind(listProperty);
显然这不起作用,因为它需要一个 ObservableList。有一种优雅的方法吗?
【问题讨论】:
标签: java multithreading queue executorservice