您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
创建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());
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。