SpringBoot(一) 多線程與異步


多線程與異步

異步是目的,而多線程是實現這個目的的方法。

1 Java J.U.C線程調度

JDK 1.5新增的java.util.concurrent包,增加了並發編程的很多類。

image-20200707230102829

Executor

定義了方法execute(),用來執行一個任務

public interface Executor {
    void execute(Runnable command);
}
ExecutorService

提供了生命周期管理的方法。

submit()

shutdown()

invokeAll()

invokeAny()

ThreadPoolExecutor

Java提供的線程池類。可自定義線程池大小及線程處理機制。

corePoolSize:線程池的基本大小,即在沒有任務需要執行的時候線程池的大小,並且只有在工作隊列滿了的情況下才會創建超出這個數量的線程。

maximumPoolSize:線程池中允許的最大線程數,線程池中的當前線程數目不會超過該值。

keepAliveTime:線程空閑時間

poolSize表示當前線程數,新提交一個任務時的處理流程為:

  • 如果當前線程池的線程數還沒有達到基本大小(poolSize < corePoolSize),無論是否有空閑的線程新增一個線程處理新提交的任務

  • 如果當前線程池的線程數大於或等於基本大小(poolSize >= corePoolSize) 且任務隊列未滿時,就將新提交的任務提交到阻塞隊列排隊,等候處理。

  • 如果當前線程池的線程數大於或等於基本大小(poolSize >= corePoolSize) 且任務隊列滿時:

    • 當前poolSize<maximumPoolSize,那么就新增線程來處理任務
    • 當前poolSize=maximumPoolSize,那么意味着線程池的處理能力已經達到了極限,此時需要拒絕新增加的任務。至於如何拒絕處理新增的任務,取決於線程池的飽和策略RejectedExecutionHandler。
ScheduledExecutorService

定時調度接口。有4種調度機制:

//帶延遲時間的調度,只執行一次,調度之后可通過Future.get()阻塞直至任務執行完畢
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
//帶延遲時間的調度,只執行一次,調度之后可通過Future.get()阻塞直至任務執行完畢,並且可以獲取執行結果
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
//帶延遲時間的調度,循環執行,固定頻率
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
//帶延遲時間的調度,循環執行,固定延遲
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
ScheduledThreadPoolExecutor

基於線程池的定時調度實現。可以用來在給定延時后執行異步任務或者周期性執行任務。

ScheduledExecutorService4種調度機制的實現。

2 Spring線程調度

image-20200707232349760

TaskExecutor

Spring引入了TaskExecutor接口作為頂層接口。繼承至J.U.C的Executor接口。

TaskScheduler

類似於J.U.C中的ScheduledExecutorService,是任務調度的接口。

功能與ScheduledExecutorService差不多,多了一個可傳Trigger對象的schedule()方法,可支持Corn表達式進行任務調度。

ScheduledFuture<?> schedule(Runnable task, Trigger trigger);
ScheduledFuture<?> schedule(Runnable task, Date startTime);
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period);
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period);
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay);
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay);
AsyncTaskExecutor

接口中提供submit()方法執行任務。

ThreadPoolTaskExecutor

Spring提供的線程池類。與Java提供的ThreadPoolExecutor線程池類類似,可以配置線程池屬性及拒絕策略。

處理流程與ThreadPoolExecutor一樣。

ThreadPoolTaskScheduler

實現TaskScheduler接口,實現了其接口的調度機制。與Java中的ScheduledThreadPoolExecutor類類似。

多了一個可傳Trigger對象的schedule()方法,可支持Corn表達式進行任務調度。

3 Spring異步操作

使用@Async注解

標注了@Async注解的方法,稱之為異步方法。這些方法將在執行的時候,將會在獨立的線程(線程池中獲取)中被執行,調用者無需等待它的完成,即可繼續其他的操作。

@Configuration
@EnableAsync
public class AsyncConfig {
    
}
@Async
public void downloadOrder() throws InterruptedException {
    System.out.println("執行開始時間為:" + LocalDateTime.now() + "線程為:" + Thread.currentThread().getName());
    Thread.sleep(10000);
    System.out.println("執行結束時間為:" + LocalDateTime.now() + "線程為:" + Thread.currentThread().getName());
}

@Async標注的方法,在同一個類中調用,無效

4 Spring定時任務的幾個實現

4.1 基於@Scheduled注解
@Configuration      //標記為配置類
@EnableScheduling   //開啟定時任務,可以放到啟動類中
public class OrderScheduler {
    //定時任務執行周期,采用Corn表達式
    @Scheduled(cron = "0/5 * * * * ?")
    public void downloadOrder() {
        System.out.println("執行開始時間為:" + LocalDateTime.now() + "線程為:" + Thread.currentThread().getName());
        Thread.sleep(10000);
        System.out.println("執行結束時間為:" + LocalDateTime.now() + "線程為:" + Thread.currentThread().getName());
    }
}
//並不是每5秒執行一次,上次執行的結果會影響到下次運行。這個相當於10s運行一次了。

@Scheduled注解也可以直接指定時間間隔,如:@Scheduled(fixedRate=5000)

實現本質是基於Java中的ScheduledExecutorService類的schedule方法。

基於@Scheduled注解默認為單線程的。

標注了@Scheduled的方法,執行時是單線程的,也就是說,上次運行的結果會影響到下一次的執行。

image-20200706233720429

4.2 基於SchedulingConfigurer接口
@FunctionalInterface
public interface SchedulingConfigurer {
	void configureTasks(ScheduledTaskRegistrar taskRegistrar);
}
ScheduledTaskRegistrar類

實現SchedulingConfigurer接口,實現configureTasks方法,方法傳入ScheduledTaskRegistrar類對象。

幾種定時任務類型:

  • CronTask:根據Cron表達式執行定時任務
  • TriggerTask:按照Trigger觸發器觸發執行,可以動態改變定時任務的執行
  • FixedRateTask:固定速度執行
  • FixedDelayTask:固定延遲執行
@EnableScheduling //啟動類,設置定時任務開關
@SpringBootApplication
public class MatrixApplication {

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

}
@Component
public class TestScheduler implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() -> System.out.println("執行時間:" + LocalDateTime.now()), new CronTrigger("0/2 * * * * ?"));
    }
}

SchedulingConfigurer配置類比@Scheduled注解多了一個TriggerTask,更加靈活,其他的差不多。

4.3 基於注解設定多線程定時任務

@Scheduled注解默認為單線程的,我們可以使用@Async注解啟用多線程。

@Configuration      //標記為配置類
@EnableAsync        //開啟多線程
@EnableScheduling   //開啟定時任務,可以放到啟動類中
public class OrderScheduler {
    //定時任務執行周期,采用Corn表達式
    @Async
    @Scheduled(cron = "0/5 * * * * ?")
    public void downloadOrder() {
        System.out.println("執行開始時間為:" + LocalDateTime.now() + "線程為:" + Thread.currentThread().getName());
        Thread.sleep(10000);
        System.out.println("執行結束時間為:" + LocalDateTime.now() + "線程為:" + Thread.currentThread().getName());
    }
}

image-20200706233756167

同一個任務的每一次定時任務執行,都會開辟一個新的線程,不會影響到下一次任務的執行。

4.4 ThreadPoolTaskScheduler

利用線程池實現任務調度。

@Resource
private ThreadPoolTaskScheduler threadPoolTaskScheduler;

@GetMapping("/start")
public void test() {
    threadPoolTaskScheduler.schedule(() -> System.out.println("第" + i + "執行時間:" + LocalDateTime.now()), new CronTrigger("0/2 * * * * ?"));
}
4.5 整合Quartz

定時任務內部的方法可以結合@Async注解使用達到多線程的目的

參考文章
  1. https://www.cnblogs.com/frankyou/p/10135212.html
  2. https://blog.csdn.net/weixin_43168010/article/details/97613895


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM