2019-05-23 @Async并行

1.常規(guī)代碼順序執(zhí)行

如下定義三個任務(wù),然后在單元測試依次調(diào)用三個任務(wù),可以看到執(zhí)行結(jié)果是先后執(zhí)行三個任務(wù),必須等待前一個任務(wù)結(jié)束后才能開始下一個任務(wù),總共耗時6000多毫秒
測試類

package com.ghw.async;

import javafx.scene.paint.Stop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {

    @Autowired
    private Task task;

    private static StopWatch stopWatch = new StopWatch();

    @Test
    public void contextLoads() {
    }

    @Test
    public void test() throws Exception {
        task.setStopWatch(stopWatch);
        task.doTaskOne();
        task.doTaskTwo();
        task.doTaskThree();
        System.out.println(stopWatch.prettyPrint());
    }
}

Task類

package com.ghw.async;

import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class Task {

    private StopWatch stopWatch;

    public void setStopWatch(StopWatch stopWatch) {
        this.stopWatch = stopWatch;
    }

    public void doTaskOne() throws Exception {
        stopWatch.start("task1");
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
    }

    public void doTaskTwo() throws Exception {
        stopWatch.start("task2");
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
    }

    public void doTaskThree() throws Exception {
        stopWatch.start("task3");
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
    }
}

執(zhí)行結(jié)果

StopWatch '': running time (millis) = 6039
-----------------------------------------
ms     %     Task name
-----------------------------------------
02014  033%  task1
02013  033%  task2
02012  033%  task3

2.采用@Async注解異步執(zhí)行

Task類

package com.ghw.async;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Component
public class Task {

    @Async
    public Future<String> doTaskOne() throws Exception {
        StopWatch stopWatch = new StopWatch();
        String task = "task1";
        stopWatch.start(task);
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
        System.out.println(task + " spend time:" + stopWatch.getLastTaskTimeMillis());
        return new AsyncResult<>(task + " is finished");
    }

    @Async
    public Future<String> doTaskTwo() throws Exception {
        StopWatch stopWatch = new StopWatch();
        String task = "task2";
        stopWatch.start(task);
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
        System.out.println(task + " spend time:" + stopWatch.getLastTaskTimeMillis());
        return new AsyncResult<>(task + " is finished");
    }

    @Async
    public Future<String> doTaskThree() throws Exception {
        StopWatch stopWatch = new StopWatch();
        String task = "task3";
        stopWatch.start(task);
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
        System.out.println(task + " spend time:" + stopWatch.getLastTaskTimeMillis());
        return new AsyncResult<>(task + " is finished");
    }
}

測試類

package com.ghw.async;

import javafx.scene.paint.Stop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {

    @Autowired
    private Task task;

    private static StopWatch stopWatch = new StopWatch();

    @Test
    public void contextLoads() {
    }

    @Test
    public void test() throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("all");
        Future<String> task1 = task.doTaskOne();
        Future<String> task2 = task.doTaskTwo();
        Future<String> task3 = task.doTaskThree();

        while (true) {
            if (task1.isDone() && task2.isDone() && task3.isDone()) {
                // 三個任務(wù)都調(diào)用完成,退出循環(huán)等待
                break;
            }
        }
        stopWatch.stop();
        System.out.println("all task spend time:" + stopWatch.getLastTaskTimeMillis());
    }
}

執(zhí)行結(jié)果

task3 spend time:2014
task1 spend time:2014
task2 spend time:2014
all task spend time:2060

可以看出只需要2060毫秒,三個任務(wù)就全部執(zhí)行完成了,相比第一種方法,能夠提高3倍速度。
其中使用Future<T>來返回異步調(diào)用的結(jié)果。在while循環(huán)中判斷,當(dāng)三個任務(wù)全部完成的時候,退出while循環(huán)。

采用自己配置的線程池

package com.ghw.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class Task {

    @Async(value = "taskExecutor")
    public void doTaskOne() throws Exception {
        log.info("開始做任務(wù)一");
        StopWatch stopWatch = new StopWatch();
        String task = "task1";
        stopWatch.start(task);
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
        log.info("完成任務(wù)一,耗時:" + (stopWatch.getLastTaskTimeMillis()) + "毫秒");
    }

    @Async(value = "taskExecutor")
    public void doTaskTwo() throws Exception {
        log.info("開始做任務(wù)二");
        StopWatch stopWatch = new StopWatch();
        String task = "task2";
        stopWatch.start(task);
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
        log.info("完成任務(wù)二,耗時:" + (stopWatch.getLastTaskTimeMillis()) + "毫秒");
    }

    @Async(value = "taskExecutor")
    public void doTaskThree() throws Exception {
        log.info("開始做任務(wù)三");
        StopWatch stopWatch = new StopWatch();
        String task = "task3";
        stopWatch.start(task);
        TimeUnit.SECONDS.sleep(2);
        stopWatch.stop();
        log.info("完成任務(wù)三,耗時:" + (stopWatch.getLastTaskTimeMillis()) + "毫秒");
    }
}
package com.ghw.async;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@SpringBootApplication
public class AsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsyncApplication.class, args);
    }

    @EnableAsync
    @Configuration
    class TaskPoolConfig {

        @Bean("taskExecutor")
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(20);
            executor.setQueueCapacity(200);
            executor.setKeepAliveSeconds(60);
            executor.setThreadNamePrefix("taskExecutor-");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            return executor;
        }
    }
}

單元測試

package com.ghw.async;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {

    @Autowired
    private Task task;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    private static StopWatch stopWatch = new StopWatch();

    @Test
    public void contextLoads() {
    }

    @Test
    public void test() throws Exception {
        task.doTaskOne();
        task.doTaskTwo();
        task.doTaskThree();
        Thread.currentThread().join();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容