Runnable Callable Future FutureTask
所属分类 java
浏览量 962
Runnable 和 Callable 区别
Callable 有返回值且可抛异常
Runnable 无返回值
Future 获取异步执行结果,并可对任务进行一些操作 (cancel 等)
FutureTask 具体实现类,实现 RunnableFuture 接口 ,
同时具备 Runnable 和 Future 特性,包装了Callable
可以把Runnable 转成 Callable ,可指定返回结果
线程池
ThreadPoolExecutor
submit 任务 返回 future
public interface Runnable {
public abstract void run();
}
public interface Callable {
V call() throws Exception;
}
public interface Future {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
public interface RunnableFuture extends Runnable, Future {
void run();
}
public class FutureTask implements RunnableFuture {
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
...
}
public static Callable callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter(task, result);
}
static final class RunnableAdapter implements Callable {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
线程池 ThreadPoolExecutor
public class ThreadPoolExecutor extends AbstractExecutorService
public abstract class AbstractExecutorService implements ExecutorService
public interface ExecutorService extends Executor
public Future> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
public Future submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
public Future submit(Callable task) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
FutureTask
public FutureTask(Callable callable)
public FutureTask(Runnable runnable, V result)
FutureTask 实例
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/conc/FutureTaskTest.java
Java线程池ExecutorService与CompletionService
上一篇
下一篇
MySQLTEXT类型最大长度
高效会议六大原则
mysql 单引号转义
老程序员的几点建议
为何不建议使用Optional
Redis性能问题排查要点