开启一个线程有三种方式定义:
Thread、Runnable、Callable,其中Runnable实现的是void run()方法,Callable实现的是 V call()方法,并且可以返回执行结果,其中Runnable可以提交给Thread来包装下,直接启动一个线程来执行,而Callable则一般都是提交给ExecuteService来执行。
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
简单来说,Executor就是Runnable和Callable的调度容器,Future就是对于具体的调度任务的执行结果进行查看,最为关键的是Future可以检查对应的任务是否已经完成,也可以阻塞在get方法上一直等待任务返回结果。Runnable和Callable的差别就是Runnable是没有结果可以返回的,就算是通过Future也看不到任务调度的结果的。
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
n isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
future的get和cancle小例子:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 创建一个执行任务的服务
ExecutorService service = Executors.newFixedThreadPool(3);
try {
// 1.Runnable通过Future返回结果
// 创建一个Runnable,来调度,等待任务执行完毕,取得返回结果
Future<?> runable = service.submit(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("runable is running");
}
});
System.out.println("runable.get():" + runable.get());
// 2.Callable通过Future能返回结果
// 提交并执行任务,任务启动时返回了一个 Future对象,
// 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作
Future<String> callable = service.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("callable is running");
return "result is callable";
}
});
System.out.println("callable.get():" + callable.get());
// 3. 对Callable调用cancel可以对对该任务进行中断
// 提交并执行任务,任务启动时返回了一个 Future对象,
Future<String> callable2 = service.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
try {
while (true) {
System.out.println("callable2 is running.");
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Interrupted callable2.");
}
return "result is callable2";
}
});
// 等待5秒后,再停止第二个任务。因为第二个任务进行的是无限循环
Thread.sleep(10);
System.out.println("callable2 cancle: " + callable2.cancel(true));
// 4.用Callable时抛出异常则Future什么也取不到了
// 获取第三个任务的输出,因为执行第三个任务会引起异常
// 所以下面的语句将引起异常的抛出
Future<String> callable3 = service.submit(new Callable<String>() {
@Override
public String call() throws Exception {
throw new Exception("callable3 throw exception!");
}
});
System.out.println("task3: " + callable3.get());
// 停止任务执行服务
service.shutdownNow();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
执行结果:
runable is running
runable.get():null
callable is running
callable.get():result is callable
callable2 is running.
callable2 cancle: true
Interrupted callable2.
java.util.concurrent.ExecutionException: java.lang.Exception: callable3 throw exception!
FutureTask实现RunnableFuture,即实现了Runnbale又实现了Futrue这两个接口,另外它还可以包装Runnable和Callable,所以一般来讲是一个复合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
futuretask例子:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class FutureTaskDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("Sleep start.");
Thread.sleep(1000 * 2);
System.out.println("Sleep end.");
return "time=" + System.currentTimeMillis();
}
};
try {
// 直接使用Thread的方式执行
FutureTask<String> ft = new FutureTask<>(callable);
new Thread(ft).start();
System.out.println("ft.get() = " + ft.get());
FutureTask<String> ft2 = new FutureTask<>(callable);
// 使用Executors来执行
System.out.println("=========");
Executors.newSingleThreadExecutor().submit(ft2);
System.out.println("ft2.get() = " + ft2.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
执行结果:
Sleep start.
Sleep end.
ft.get() = time=1481081318178
=========
Sleep start.
Sleep end.
ft2.get() = time=1481081320188