Java基础系列:多线程的同步和异步

1 场景

多线程有两种应用场景:纯异步场景,与“同步”场景。
其中,

  • 纯异步场景
    即线程A顺序执行的程序中,添加了线程B处理某个任务,线程A优先返回结果,让调用者可以快速拿到结果,不至于线程A耗时过长而出现阻塞,线程B在返回结果后继续执行任务(可能会出现执行失败,而无法直接告知调用者,需要引入补偿机制),不影响结果的返回,即异步处理。
  • “同步”场景
    即线程执行的任务具有返回值,并且需要拿到当前的返回值继续进行执行,使用Future作为返回的类型,此时,多线程的异步已经不是异步执行,而是“同步”执行,因为需要等待线程执行的结果。

2 Test

2.1 同步

package thread;

import java.util.concurrent.*;
import java.util.logging.Logger;

import static common.constant.DigitalConstant.*;

/**
 * ThreadPoolExecutor测试.
 *
 * @author xindaqi
 * @date 2021-04-28 17:58
 */
public class ThreadPoolExecutorTestOne {

    private static Logger logger = Logger.getLogger("ThreadPoolExecutorTestOne");

    /**
     * 有返回值测试.
     *
     * @return
     * @throws InterruptedException
     */
    private static String testWithReturn() throws InterruptedException {
        logger.info("当前线程:" + Thread.currentThread().getName());
        Thread.sleep(FIVE*THOUSAND_L);
        return Thread.currentThread().getName();
    }

    /**
     * 无返回值测试.
     *
     * @return
     * @throws InterruptedException
     */
    private static String testWithoutReturn() throws InterruptedException {
        logger.info("当前线程:" + Thread.currentThread().getName());
        Thread.sleep(FIVE*THOUSAND_L);
        return Thread.currentThread().getName();
    }

    public static void AsynchronizedTest(ExecutorService executorService, Integer flag) {
        switch(flag) {
            case ONE:
                try {
                    Future<String> future = executorService.submit(() -> testWithReturn());
                    logger.info("Future content:" + future.get());
                    logger.info("我有返回值,是同步");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                } finally {
                    executorService.shutdown();
                    break;
                }
            case TWO:
                try {
                    executorService.submit(() -> testWithoutReturn());
                    logger.info("我没有返回值,是异步");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    executorService.shutdown();
                    break;
                }
            default:
                logger.info("不匹配");
        }

    }
    public static void main(String[] args) {
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(
                THREE,
                FIVE,
                THOUSAND_L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(TWO),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        AsynchronizedTest(threadPoolExecutor, ONE);
    }

}
  • 结果
    四月 28, 2021 6:56:23 下午 thread.ThreadPoolExecutorTestOne testWithReturn
    信息: 当前线程:pool-1-thread-1
    四月 28, 2021 6:56:28 下午 thread.ThreadPoolExecutorTestOne AsynchronizedTest
    信息: Future content:pool-1-thread-1
    四月 28, 2021 6:56:28 下午 thread.ThreadPoolExecutorTestOne AsynchronizedTest
    信息: 我有返回值,是同步
  • 分析
    由运行结果可知,使用Future获取线程执行结果,是顺序执行,同步而非异步。

2.2 异步

package thread;

import java.util.concurrent.*;
import java.util.logging.Logger;

import static common.constant.DigitalConstant.*;

/**
 * ThreadPoolExecutor测试.
 *
 * @author xindaqi
 * @date 2021-04-28 17:58
 */
public class ThreadPoolExecutorTestOne {

    private static Logger logger = Logger.getLogger("ThreadPoolExecutorTestOne");

    /**
     * 有返回值测试.
     *
     * @return
     * @throws InterruptedException
     */
    private static String testWithReturn() throws InterruptedException {
        logger.info("当前线程:" + Thread.currentThread().getName());
        Thread.sleep(FIVE*THOUSAND_L);
        return Thread.currentThread().getName();
    }

    /**
     * 无返回值测试.
     *
     * @return
     * @throws InterruptedException
     */
    private static String testWithoutReturn() throws InterruptedException {
        logger.info("当前线程:" + Thread.currentThread().getName());
        Thread.sleep(FIVE*THOUSAND_L);
        return Thread.currentThread().getName();
    }

    public static void AsynchronizedTest(ExecutorService executorService, Integer flag) {
        switch(flag) {
            case ONE:
                try {
                    Future<String> future = executorService.submit(() -> testWithReturn());
                    logger.info("Future content:" + future.get());
                    logger.info("我有返回值,是同步");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                } finally {
                    executorService.shutdown();
                    break;
                }
            case TWO:
                try {
                    executorService.submit(() -> testWithoutReturn());
                    logger.info("我没有返回值,是异步");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    executorService.shutdown();
                    break;
                }
            default:
                logger.info("不匹配");
        }

    }
    public static void main(String[] args) {
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(
                THREE,
                FIVE,
                THOUSAND_L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(TWO),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        AsynchronizedTest(threadPoolExecutor, TWO);

    }

}
  • 结果
    四月 28, 2021 6:52:59 下午 thread.ThreadPoolExecutorTestOne AsynchronizedTest
    信息: 我没有返回值,是异步
    四月 28, 2021 6:52:59 下午 thread.ThreadPoolExecutorTestOne testWithoutReturn
    信息: 当前线程:pool-1-thread-1
  • 分析
    由运行结果可知,线程执行结果,是异步,先执行第二个结果: 我没有返回值,是异步,然后异步执行线程中的另一个任务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值