【发布时间】:2018-08-13 21:01:35
【问题描述】:
我正在开发一个 JavaFX 应用程序,并在 ExecutorService submit 方法中提供 JavaFX 任务。我还试图在Future 对象中的提交返回值中获取Task 的返回值。然后我发现ExecutorService 仅在您提交Callable 对象时才返回值,并且尽管有call 方法,JavaFX 任务仍然是可运行的。那么这个问题有什么解决方法吗?
我尝试过并以这种方式解决了我的问题,但当我不想编写自己的课程时,我愿意接受建议。
我的主要方法:
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Semaphore semaphore = new Semaphore(1);
List<Integer> list = IntStream.range(0,100).boxed().collect(Collectors.toList());
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
List<Integer> sendingList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
sendingList.add(iterator.next());
}
System.out.println("SUBMITTING");
Future<Integer> future = executorService.submit((Callable<Integer>) new TestCallable(sendingList,semaphore));
System.out.println(future.get());
semaphore.acquire();
}
executorService.shutdown();
System.out.println("COMPLETED");
}
我的TestCallable班级:
class TestCallable extends Task<Integer> implements Callable<Integer> {
private Random random = new Random();
private List<Integer> list;
private Semaphore semaphore;
TestCallable(List<Integer> list, Semaphore semaphore) {
this.list = list;
this.semaphore = semaphore;
}
@Override
public Integer call(){
System.out.println("SENDING");
System.out.println(list);
try {
Thread.sleep(1000+random.nextInt(500));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("RECEIVED");
semaphore.release();
return list.size();
}
}
【问题讨论】:
-
您确实注意到 a)
Task实现了Futureb) 提交任务并立即调用get导致在调用线程中等待任务完成。你可以直接在线程上执行任务。 -
如果我有一个多线程执行器,如果没有可用线程,我想等待,而不是每个任务?
-
打电话给
Future.get你一定要等到任务完成。假设提交线程和执行任务的线程具有相同的优先级,在不同的线程上运行任务并不会更快,并且即使使用多线程执行器也不会导致任何任务并行运行。在这种情况下提交任务会将工作从一个线程转移到另一个线程,并使提交任务忙于等待任务完成...
标签: java multithreading javafx