标签:start sub boolean 定义 row except pre 取消 exec
一. Callable接口与Runnable接口区别创建java线程,我们经常使用两种方式:
但这两种方式有一个缺陷:在执行完任务之后无法直接获取执行结果。
public interface Callable<V> {
V call() throws Exception;
}
public interface Runnable {
public abstract void run();
}
public?interface?Future<V> {
????boolean?cancel(boolean?mayInterruptIfRunning);
????boolean?isCancelled();
????boolean?isDone();
????V get()?throws?InterruptedException, ExecutionException;
????V get(long?timeout, TimeUnit unit)
????????throws?InterruptedException, ExecutionException, TimeoutException;
}
public?class?FutureTask<V>?implements?RunnableFuture<V>
public?interface?RunnableFuture<V>?extends?Runnable, Future<V> {
????void?run();
}
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("线程执行中...");
}
};
Thread thread = new Thread(runnable);
thread.start();
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("线程执行中...");
return 100;
}
};
FutureTask < Integer > futureTask = new FutureTask < Integer > (callable);
new Thread(futureTask).start();
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("获取执行结果:" + futureTask.get());
}
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("线程执行中...");
return 100;
}
};
ExecutorService service = Executors.newCachedThreadPool();
Future < Integer > future = service.submit(callable);
// 等待1秒,让线程执行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("获取执行结果:" + future.get());
}
Callable、FutureTask和Future详解带你理解java并发编程
标签:start sub boolean 定义 row except pre 取消 exec
原文地址:https://blog.51cto.com/634435/2476201