java 开启一个线程可以使用thread 也可以使用runnable
在jdk1.5 之后有一个callable 类 同样可以开启一个线程:
优势:
1:支持返回值(包含计算结果的future对象)
2:任务可以取消 可以检查是否完成
callable 源码:
public interface Callable<V> {
V call() throws Exception;
}
fature 源码;
public interface Future<V> {
boolean cancel(boolean var1);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long var1, TimeUnit var3) throws InterruptedException, ExecutionException, TimeoutException;
}
可以看到future 非常适合android app 这样有生命周期的activity 可以取消 可以检查是否完成...
cancel 方法: 对任务执行取消
isDone 任务完结束返回true(正常结束,异常或者取消都返回true)
get 获取计算结果
如果想要是用fature ,还得看thread的 构造参数
thread 的构造参数中最近的就是传递一个rannable
runnable有一个子类 fatureTask
public class FutureTask<V> implements Future<V>, Runnable {
public FutureTask(Callable<V> callable) {
throw new RuntimeException("Stub!");
}
public FutureTask(Runnable runnable, V result) {
throw new RuntimeException("Stub!");
}
public boolean isCancelled() {
throw new RuntimeException("Stub!");
}
public boolean isDone() {
throw new RuntimeException("Stub!");
}
public boolean cancel(boolean mayInterruptIfRunning) {
throw new RuntimeException("Stub!");
}
public V get() throws InterruptedException, ExecutionException {
throw new RuntimeException("Stub!");
}
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
throw new RuntimeException("Stub!");
}
protected void done() {
throw new RuntimeException("Stub!");
}
protected void set(V v) {
throw new RuntimeException("Stub!");
}
protected void setException(Throwable t) {
throw new RuntimeException("Stub!");
}
public void run() {
throw new RuntimeException("Stub!");
}
protected boolean runAndReset() {
throw new RuntimeException("Stub!");
}
}
正好传递给thread
使用例子:
Callable<String> stringCallable = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "my name is xuan";
}
};
FutureTask<String> futureTask = new FutureTask<String>(stringCallable);
Thread thread = new Thread(futureTask);
thread.start();
/* if (!futureTask.isDone() && !futureTask.isCancelled())
futureTask.cancel(true);
System.out.println("------>thread:"+futureTask.get());*/