前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Java 中 Future 的 get 方法超时会怎样?

Java 中 Future 的 get 方法超时会怎样?

作者头像
明明如月学长
发布于 2022-06-15 04:59:26
发布于 2022-06-15 04:59:26
4.1K00
代码可运行
举报
运行总次数:0
代码可运行

一、背景

很多 Java 工程师在准备面试时,会刷很多八股文,线程和线程池这一块通常会准备线程的状态、线程的创建方式,Executors 里面的一些工厂方法和为什么不推荐使用这些工厂方法,ThreadPoolExecutor 构造方法的一些参数和执行过程等。

工作中,很多人会使用线程池的 submit 方法 获取 Future 类型的返回值,然后使用 java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) 实现“最多等多久”的效果。

但很多人对此的理解只停留在表面上,稍微问深一点点可能就懵逼了。

比如,java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) 超时之后,当前线程会怎样?线程池里执行对应任务的线程会有怎样的表现?

如果你对这个问题没有很大的把握,说明你掌握的还不够扎实。

最常见的理解就是,“超时以后,当前线程继续执行,线程池里的对应线程中断”,真的是这样吗?

二、模拟

2.1 常见写法

下面给出一个简单的模拟案例:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package basic.thread;

import java.util.concurrent.*;

public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Future<?> future = executorService.submit(() -> {
            try {
                demo();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + "获取的结果 -- start");
        Object result = future.get(100, TimeUnit.MILLISECONDS);
        System.out.println(threadName + "获取的结果 -- end :" + result);

    }

    private static String demo() throws InterruptedException {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + ",执行 demo -- start");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(threadName + ",执行 demo -- end");
        return "test";
    }
}

输出结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
main获取的结果 -- start
pool-1-thread-1,执行 demo -- start
Exception in thread "main" java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at basic.thread.FutureDemo.main(FutureDemo.java:20)
pool-1-thread-1,执行 demo -- end

我们可以发现:当前线程会因为收到 TimeoutException 而被中断,线程池里对应的线程“却”继续执行完毕。

2.2 尝试取消

我们尝试对未完成的线程进行取消,发现 Future#cancel 有个 boolean 类型的参数。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

看源码注释我们可以知道:

当设置为 true 时,正在执行的任务将被中断(interrupted);

当设置为 false 时,如果任务正在执行中,那么仍然允许任务执行完成。

2.2.1 cancel(false)

此时,为了不让主线程因为超时异常被中断,我们 try-catch 包起来。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package basic.thread;

import org.junit.platform.commons.util.ExceptionUtils;

import java.util.concurrent.*;

public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Future<?> future = executorService.submit(() -> {
            try {
                demo();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- start");
        try {
            Object result = future.get(100, TimeUnit.MILLISECONDS);
            System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- end :" + result);
        } catch (Exception e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果异常:" + ExceptionUtils.readStackTrace(e));
        }
        future.cancel(false);
        System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- cancel");
    }

    private static String demo() throws InterruptedException {
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + ",执行 demo -- start");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(System.currentTimeMillis() + "," + threadName + ",执行 demo -- end");
        return "test";
    }
}

结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1653751759233,main获取的结果 -- start
1653751759233,pool-1-thread-1,执行 demo -- start
1653751759343,main获取的结果异常:java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at basic.thread.FutureDemo.main(FutureDemo.java:23)

1653751759351,main获取的结果 -- cancel
1653751760263,pool-1-thread-1,执行 demo -- end

我们发现,线程池里的对应线程在 cancel(false) 时,如果已经正在执行,则会继续执行完成。

2.2.2 cancel(true)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package basic.thread;

import org.junit.platform.commons.util.ExceptionUtils;

import java.util.concurrent.*;

public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Future<?> future = executorService.submit(() -> {
            try {
                demo();
            } catch (InterruptedException e) {
                System.out.println(System.currentTimeMillis() + "," + Thread.currentThread().getName() + ", Interrupted:" + ExceptionUtils.readStackTrace(e));
                throw new RuntimeException(e);
            }
        });

        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- start");
        try {
            Object result = future.get(100, TimeUnit.MILLISECONDS);
            System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- end :" + result);
        } catch (Exception e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果异常:" + ExceptionUtils.readStackTrace(e));
        }
        future.cancel(true);
        System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- cancel");
    }

    private static String demo() throws InterruptedException {
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + ",执行 demo -- start");
        TimeUnit.SECONDS.sleep(1);
        System.out.println(System.currentTimeMillis() + "," + threadName + ",执行 demo -- end");
        return "test";
    }
}

执行结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1653752011246,main获取的结果 -- start
1653752011246,pool-1-thread-1,执行 demo -- start
1653752011347,main获取的结果异常:java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at basic.thread.FutureDemo.main(FutureDemo.java:24)

1653752011363,pool-1-thread-1, Interrupted:java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at java.lang.Thread.sleep(Thread.java:340)
	at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
	at basic.thread.FutureDemo.demo(FutureDemo.java:36)
	at basic.thread.FutureDemo.lambda$main$0(FutureDemo.java:14)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)

1653752011366,main获取的结果 -- cancel

可以看出,此时,如果目标线程未执行完,那么会收到 InterruptedException ,被中断。

当然,如果此时不希望目标线程被中断,可以使用 try-catch 包住,再执行其他逻辑。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package basic.thread;

import org.junit.platform.commons.util.ExceptionUtils;

import java.util.concurrent.*;

public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Future<?> future = executorService.submit(() -> {
            demo();
        });

        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- start");
        try {
            Object result = future.get(100, TimeUnit.MILLISECONDS);
            System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- end :" + result);
        } catch (Exception e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果异常:" + ExceptionUtils.readStackTrace(e));
        }
        future.cancel(true);
        System.out.println(System.currentTimeMillis() + "," + threadName + "获取的结果 -- cancel");
    }

    private static String demo() {
        String threadName = Thread.currentThread().getName();
        System.out.println(System.currentTimeMillis() + "," + threadName + ",执行 demo -- start");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            System.out.println(System.currentTimeMillis() + "," + threadName + ",执行 demo 被中断,自动降级");
        }
        System.out.println(System.currentTimeMillis() + "," + threadName + ",执行 demo -- end");
        return "test";
    }
}

执行结果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1653752219803,main获取的结果 -- start
1653752219803,pool-1-thread-1,执行 demo -- start
1653752219908,main获取的结果异常:java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at basic.thread.FutureDemo.main(FutureDemo.java:19)

1653752219913,main获取的结果 -- cancel
1653752219914,pool-1-thread-1,执行 demo 被中断,自动降级
1653752219914,pool-1-thread-1,执行 demo -- end

三、回归源码

我们直接看 java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) 的源码注释,就可以清楚地知道各种情况的表现:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

我们还可以选取几个常见的实现类,查看下实现的基本思路:

java.util.concurrent.FutureTask#get(long, java.util.concurrent.TimeUnit)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
   public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

java.util.concurrent.CompletableFuture#get(long, java.util.concurrent.TimeUnit)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Waits if necessary for at most the given time for this future
     * to complete, and then returns its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the result value
     * @throws CancellationException if this future was cancelled
     * @throws ExecutionException if this future completed exceptionally
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    public T get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        Object r;
        long nanos = unit.toNanos(timeout);
        return reportGet((r = result) == null ? timedGet(nanos) : r);
    }
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
  /**
     * Returns raw result after waiting, or null if interrupted, or
     * throws TimeoutException on timeout.
     */
    private Object timedGet(long nanos) throws TimeoutException {
        if (Thread.interrupted())
            return null;
        if (nanos <= 0L)
            throw new TimeoutException();
        long d = System.nanoTime() + nanos;
        Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0
        boolean queued = false;
        Object r;
        // We intentionally don't spin here (as waitingGet does) because
        // the call to nanoTime() above acts much like a spin.
        while ((r = result) == null) {
            if (!queued)
                queued = tryPushStack(q);
            else if (q.interruptControl < 0 || q.nanos <= 0L) {
                q.thread = null;
                cleanStack();
                if (q.interruptControl < 0)
                    return null;
                throw new TimeoutException();
            }
            else if (q.thread != null && result == null) {
                try {
                    ForkJoinPool.managedBlock(q);
                } catch (InterruptedException ie) {
                    q.interruptControl = -1;
                }
            }
        }
        if (q.interruptControl < 0)
            r = null;
        q.thread = null;
        postComplete();
        return r;
    }

java.util.concurrent.Future#cancel 也一样

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * Attempts to cancel execution of this task.  This attempt will
 * fail if the task has already completed, has already been cancelled,
 * or could not be cancelled for some other reason. If successful,
 * and this task has not started when {@code cancel} is called,
 * this task should never run.  If the task has already started,
 * then the {@code mayInterruptIfRunning} parameter determines
 * whether the thread executing this task should be interrupted in
 * an attempt to stop the task.
 *
 * After this method returns, subsequent calls to {@link #isDone} will
 * always return {@code true}.  Subsequent calls to {@link #isCancelled}
 * will always return {@code true} if this method returned {@code true}.
 *
 * @param mayInterruptIfRunning {@code true} if the thread executing this
 * task should be interrupted; otherwise, in-progress tasks are allowed
 * to complete
 * @return {@code false} if the task could not be cancelled,
 * typically because it has already completed normally;
 * {@code true} otherwise
 */
boolean cancel(boolean mayInterruptIfRunning);

java.util.concurrent.FutureTask#cancel

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

可以看到 mayInterruptIfRunning 为 true 时,会执行 Thread#interrupt 方法

java.util.concurrent.CompletableFuture#cancel

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * If not already completed, completes this CompletableFuture with
     * a {@link CancellationException}. Dependent CompletableFutures
     * that have not already completed will also complete
     * exceptionally, with a {@link CompletionException} caused by
     * this {@code CancellationException}.
     *
     * @param mayInterruptIfRunning this value has no effect in this
     * implementation because interrupts are not used to control
     * processing.
     *
     * @return {@code true} if this task is now cancelled
     */
    public boolean cancel(boolean mayInterruptIfRunning) {
        boolean cancelled = (result == null) &&
            internalComplete(new AltResult(new CancellationException()));
        postComplete();
        return cancelled || isCancelled();
    }

通过注释我们也发现,不同的实现类对参数的“效果”也有差异。

四、总结

我们学习时不应该想当然,不能纸上谈兵,对于不太理解的地方,可以多看源码注释,多看源码,多写 DEMO 去模拟或调试。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022/06/14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
java高并发系列 - 第19天:JUC中的Executor框架详解1
Executors框架是Doug Lea的神作,通过这个框架,可以很容易的使用线程池高效地处理并行任务。
路人甲Java
2019/12/10
8280
Java并发编程之Future和FutureTask
搞过Java或者客户端Android开发的都知道,创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口。不过,这2种方式都有一个缺陷,就是在执行完任务之后无法获取执行结果。
xiangzhihong
2022/11/30
3510
【Java多线程-3】Future与FutureTask
前文中我们讲述了创建线程的2种方式:直接继承Thread和实现Runnable接口,但这两种方式在执行完任务之后都无法获取执行结果。 自从Java 5开始,JDK提供了Callable和Future,解决了上述问题,通过它们可以在任务执行完毕之后得到任务执行结果。
云深i不知处
2020/09/16
3680
Callable与Future介绍
在Java中,创建线程一般有两种方式,一种是继承Thread类,一种是实现Runnable接口。然而,这两种方式的缺点是在线程任务执行结束后,无法获取执行结果。我们一般只能采用共享变量或共享存储区以及线程通信的方式实现获得任务结果的目的。不过,Java中,也提供了使用Callable和Future来实现获取任务结果的操作。Callable用来执行任务,产生结果,而Future用来获得结果。
HLee
2021/10/13
1K0
Callable与Future介绍
J.U.C源码实战:Future编码实战与优缺点
在现代并发编程中,Java 的 Future 接口提供了一种处理异步计算结果的机制。Future 是 Java 5 中引入的 java.util.concurrent 包的一部分,用于表示一个任务的未来结果。随着应用程序需求的复杂化和多线程编程的普及,理解和运用 Future 变得尤为重要。本篇文章将深入探讨 Java 中 Future 的概念、使用方法及其在实际编程中的应用场景。通过学习这篇文章,读者将能够掌握如何使用 Future 接口进行异步操作,提升程序的性能和响应速度。此外,我们还将介绍与 Future 相关的其他关键类和接口,如 Callable 和 ExecutorService,以帮助读者全面了解并发编程的相关知识。无论你是刚接触 Java 并发编程的新手,还是希望深入理解和优化异步任务处理的开发者,这篇文章都将为你提供有价值的指导和参考。让我们一同开启对 Java Future 的学习之旅,探索并发编程的奥秘。
怒放吧德德
2024/06/23
1700
Java中的Runnable、Callable、Future、FutureTask的区别
Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。
开发者技术前线
2020/11/23
4210
【小家java】一个例子让就能你彻底理解Java的Future模式,Future类的设计思想
Future模式有点类似于网上购物,在你购买商品,订单生效之后,你可以去做自己的事情,等待商家通过快递给你送货上门。Future模式就是,当某一程序提交请求,期望得到一个答复。但是可能服务器程序对这个请求的处理比较慢,因此不可能马上收到答复。但是,在传统的单线程环境下,调用函数是同步的,它必须等到服务程序返回结果,才能继续进行其他处理。而Future模式下,调用方法是异步的,原本等待返回的时间段,在主调函数中,则可以处理其他的任务。传统的串行程序调用如下图所示:
YourBatman
2019/09/03
2K0
【小家java】一个例子让就能你彻底理解Java的Future模式,Future类的设计思想
高并发之——两种异步模型与深度解析Future接口
本文有点长,但是满满的干货,以实际案例的形式分析了两种异步模型,并从源码角度深度解析Future接口和FutureTask类,希望大家踏下心来,打开你的IDE,跟着文章看源码,相信你一定收获不小!
冰河
2020/10/29
5070
Java 异步编程实战之基于 JDK 中的 Future 实现异步编程|送书
本节主要讲解如何使用JDK中的Future实现异步编程,这包含如何使用FutureTask实现异步编程以及其内部实现原理以及FutureTask的局限性。
江南一点雨
2020/01/13
1.8K1
Java 异步编程实战之基于 JDK 中的 Future 实现异步编程|送书
异步编程 - 04 基于JDK中的Future实现异步编程(上)_Future & FutureTask 源码解析
在Java并发包(JUC包)中Future代表着异步计算结果,Future中提供了一系列方法用来
小小工匠
2023/09/07
2400
异步编程 - 04 基于JDK中的Future实现异步编程(上)_Future & FutureTask 源码解析
Java 还有第三种创建多线程的方式?
我们在多线程编程中最常用的两种方式:一种是直接继承Thread,另外一种就是实现Runnable接口。这两种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。
互扯程序
2019/06/19
4760
不会用Java Future,我怀疑你泡茶没我快, 又是超长图文!!
现陆续将Demo代码和技术文章整理在一起 Github实践精选 ,方便大家阅读查看,本文同样收录在此,觉得不错,还请Star
用户4172423
2020/07/14
5590
利用LockSupport实现简单Future
上篇文章已经讲到了LockSupport提供的功能,以及如何使用LockSupport实现锁的语义,本文将介绍Future的语义以及如何利用LockSupport实现Future。
LNAmp
2018/09/05
3650
【小家Java】Future与FutureTask的区别与联系
所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法。在 Java 语言中,简单的讲就是另启一个线程来完成调用中的部分计算,使调用继续运行或返回,而不需要等待计算结果。但调用者仍需要取线程的计算结果。
YourBatman
2019/09/03
2.2K0
刚研究完Callable和Future,各位随便问!!
在Java的多线程编程中,除了Thread类和Runnable接口外,不得不说的就是Callable接口Future接口了。使用继承Thread类或者实现Runnable接口的线程,无法返回最终的执行结果数据,只能等待线程执行完成。此时,如果想要获取线程执行后的返回结果,那么,Callable和Future就派上用场了。
冰河
2021/04/30
6610
Future和Callable学习
我们知道使用多线程时,最初的Thread到线程池,此时对于线程的使用,提供了其使用的复用率。而实现多线程的三种方式:继承Thread;实现Runnable接口,重写run方法;实现Callable接口,同时重写call方法,同时通过Future获取执行的返回值。也就是说callable执行任务,而Future拿到执行的结果。Future具有阻塞性在于其get()方法具有阻塞性,而isDone()是不具有阻塞性的。
路行的亚洲
2020/07/16
4850
Future Java
Future是多线程开发中常见的一种设计模式。Future模式可以返回线程执行结果的契约,通过此契约程序可以选择在合适的时机取回执行的结果,如果取回结果时线程还没有执行完成,将会阻塞调用线程等待执行结果返回。
shysh95
2021/06/10
4060
Future Java
jdk中的简单并发,需要掌握
    小时候有一次爸爸带我去偷村头别人家的梨子,我上树摘,爸爸在下面放风,正摘着主人来了,爸爸指着我破口大骂:臭小子,赶紧给我滚下来,敢偷吃别人家梨子,看我不打死你。主人家赶紧说:没事没事,小孩子淘气嘛,多摘点回家吃。我……这坑儿子的爹...
青石路
2019/02/25
3820
jdk中的简单并发,需要掌握
Java并发编程:如何创建线程?
在 Java 中创建线程的方式有两种:1)继承 Thread 类  2)实现 Runnable 接口 3)实现 FutureTask 接口 前两种方式创建的线程都无法获取线程的执行结果,而通过 FutureTask 方式实现的线程可以获取线程执行的结果。 一、继承Thread类 package com.chanshuyi.thread; public class ThreadDemo1 { public static void main(String[] args) { ne
陈树义
2018/04/13
6900
Java并发编程:如何创建线程?
(77) 异步任务执行服务 / 计算机程序的思维逻辑
Java并发包提供了一套框架,大大简化了执行异步任务所需的开发,本节我们就来初步探讨这套框架。 在之前的介绍中,线程Thread既表示要执行的任务,又表示执行的机制,而这套框架引入了一个"执行服务"的概念,它将"任务的提交"和"任务的执行"相分离,"执行服务"封装了任务执行的细节,对于任务提交者而言,它可以关注于任务本身,如提交任务、获取结果、取消任务,而不需要关注任务执行的细节,如线程创建、任务调度、线程关闭等。 以上描述可能比较抽象,接下来,我们会一步步具体阐述。 基本接口 首先,我们来看任务执行
swiftma
2018/01/31
8050
推荐阅读
相关推荐
java高并发系列 - 第19天:JUC中的Executor框架详解1
更多 >
领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文