由于使用ExecutorService可submit一个Callable任务并返回Future,为什么需要使用FutureTask包装Callable的任务和使用的方法execute?我觉得他们都做同样的事情.
需要确认一下.以下代码:
CompletableFuture
.supplyAsync(() -> {return doSomethingAndReturnA();})
.thenApply(a -> convertToB(a));
Run Code Online (Sandbox Code Playgroud)
会是这样的:
CompletableFuture
.supplyAsync(() -> {
A a = doSomethingAndReturnA();
convertToB(a);
});
Run Code Online (Sandbox Code Playgroud)
对?
此外,另外两个问题是"我们有什么理由使用thenApply?"
1)有大转换代码?
要么
2)需要在其他地方重用lambda块吗?
首先,我必须说我对API java.util.concurrent很新,所以也许我正在做的是完全错误的.
我想做什么?
我有一个Java应用程序,基本上运行2个单独的处理(称为myFirstProcess,mySecondProcess),但这些处理必须同时运行.
所以,我试着这样做:
public void startMyApplication() {
ExecutorService executor = Executors.newFixedThreadPool(2);
FutureTask<Object> futureOne = new FutureTask<Object>(myFirstProcess);
FutureTask<Object> futureTwo = new FutureTask<Object>(mySecondProcess);
executor.execute(futureOne);
executor.execute(futureTwo);
while (!(futureOne.isDone() && futureTwo.isDone())) {
try {
// I wait until both processes are finished.
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
logger.info("Processing finished");
executor.shutdown();
// Do some processing on results
...
}
Run Code Online (Sandbox Code Playgroud)
myFirstProcess和mySecondProcess是实现的类Callable<Object>,并且在call()方法中进行所有处理.
它工作得很好,但我不确定这是正确的方法.是一个做我想要的好方法吗?如果没有,你能给我一些提示来增强我的代码(并尽可能保持简单).
我只是在探索java.util.concurrent包.
我了解到类' Future '有一个方法boolean cancel(boolean mayInterruptIfRunning)
请查找附上我写的测试代码:
package com.java.util.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
public class FutureTester {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
int poolCnt = 1;
Callable<NumberPrinter> numberPrinter = null;
ScheduledThreadPoolExecutor schPool = new ScheduledThreadPoolExecutor(
poolCnt);
ScheduledFuture<NumberPrinter>[] numPrinterFutures = new ScheduledFuture[poolCnt];
FutureTask<NumberPrinter>[] futureTask = new FutureTask[poolCnt];
for (int i = 0; i < poolCnt; i++) {
numberPrinter = new …Run Code Online (Sandbox Code Playgroud) 我经常搜索,但找不到解决问题的方法.
我有自己的类,BaseTask使用a ThreadPoolExecutor来处理任务.
如果我不想要优先级(即使用a PriorityBlockingQueue),这可以正常工作,但当我尝试使用ClassCastException我得到的ThreadPoolExecutor因为FutureTask将我的任务包装到一个FutureTask对象中.
这显然是可以的,因为Comparable它没有实现newTaskFor(),但我将如何继续解决优先级问题?
我读过您可以覆盖ThreadPoolExecutor在BaseTask,但我似乎无法在所有发现这个方法...?
我们欢迎所有的建议!
一些代码可以帮助:
在我的BaseFutureTask班上,我有
private static final BlockingQueue<Runnable> sWorkQueue = new PriorityBlockingQueue<Runnable>();
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BaseThreadPoolExecutor sExecutor = new BaseThreadPoolExecutor(
1, Integer.MAX_VALUE, …Run Code Online (Sandbox Code Playgroud) 在发现在Java 1.6上FutureTask运行Executors.newCachedThreadPool()(以及从Eclipse中)吞下Runnable.run()方法中的异常后,我试图找到一种方法来捕获这些,而不向我的所有Runnable实现添加throw/catch .
API建议覆盖FutureTask.setException()应该有助于此:
导致此未来报告ExecutionException,并将给定的throwable作为其原因,除非已设置或已取消此Future.在计算失败时,run方法在内部调用此方法.
但是,似乎没有调用此方法(使用调试器运行显示异常被捕获FutureTask但setException未被调用).我写了以下程序来重现我的问题:
public class RunTest {
public static void main(String[] args) {
MyFutureTask t = new MyFutureTask(new Runnable() {
@Override
public void run() {
throw new RuntimeException("Unchecked exception");
}
});
ExecutorService service = Executors.newCachedThreadPool();
service.submit(t);
}
}
public class MyFutureTask extends FutureTask<Object> {
public MyFutureTask(Runnable r) {
super(r, null);
}
@Override
protected void setException(Throwable t) {
super.setException(t);
System.out.println("Exception: " + t);
} …Run Code Online (Sandbox Code Playgroud) 我想取消从ThreadPoolExecutor获取的FutureTask,但我想确保线程池上的Callable已经停止了它的工作.
如果我调用FutureTask#cancel(false)然后调用get()(阻塞直到完成),我会得到一个CancelledException.是立即抛出此异常还是在任务停止执行后抛出异常?
我需要安排一些将来要完成的工作.我可以用两种方式做到:
创建TimerTask并执行timer.schedule(...);
用途Executors.newScheduledThreadPool(1):
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture <?> scheduleHandle = scheduler.schedule(pushExternalRunnable,
runScheduleDate.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)这两种方式在未来安排工作有什么区别?
我想处理ThreadPoolExecutor#afterExecute()方法中工作线程抛出的exeptions .目前我有这个代码:
public class MyExecutor extends ThreadPoolExecutor {
public static void main(String[] args) {
MyExecutor threadPool = new MyExecutor();
Task<Object> task = new Task<>();
threadPool.submit(task);
}
public MyExecutor() {
super(4, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(4000));
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
System.out.println("in afterExecute()");
if (t != null) {
System.out.println("exception thrown: " + t.getMessage());
} else {
System.out.println("t == null");
}
}
private static class Task<V> implements Callable<V> {
@Override
public V call() throws …Run Code Online (Sandbox Code Playgroud) java multithreading futuretask threadpool threadpoolexecutor
我对执行者服务很陌生.喜欢自己做所有事情,但我认为是时候相信这些服务了.
我想交Executer一个Runnable.执行者FutureTask把它包裹起来并交给我.现在我调用poll done()方法.但是我希望在done()方法返回true 时得到通知.
有一种get()方法可以阻塞直到Runnable完成,但是我需要为每个作业添加一个额外的线程,只是为了看它何时完成.
我可以给我的执行者一些额外的工作,Callable以获得有关完成任务的通知吗?
怎么去这里?我可以在run方法的末尾添加一些代码,但后来done()可能仍然是假的...
futuretask ×10
java ×9
threadpool ×4
concurrency ×3
callable ×2
executor ×1
future ×1
java-8 ×1
timer ×1