03. spring 線程池與異步編程

線程池創(chuàng)建類

package org.pzy.spring.complex;

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

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import lombok.Data;

@Component
@Configurable
@ConfigurationProperties(prefix = "myThreadPool")
@Data
public class ThreadPoolConfiguration {

  private int corePoolSize;
  private int maxPoolSize;
  private int queueCapacity;
  private int keepAliveSeconds;

  @Bean
  public Executor testMyThreadPool01() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setQueueCapacity(queueCapacity);
    executor.setKeepAliveSeconds(keepAliveSeconds);
    executor.setThreadNamePrefix("my-thread-pool-01");
    // 當(dāng)線程池已滿,且等待隊(duì)列也滿了的時(shí)候,轉(zhuǎn)為主線程執(zhí)行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
  }

  @Bean
  public Executor testMyThreadPool02() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setQueueCapacity(queueCapacity);
    executor.setKeepAliveSeconds(keepAliveSeconds);
    executor.setThreadNamePrefix("my-thread-pool-02");
    // 當(dāng)線程池已滿,且等待隊(duì)列也滿了的時(shí)候,拋出TaskRejectedException
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
    executor.initialize();
    return executor;
  }

  @Bean
  public Executor testMyThreadPool03() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setQueueCapacity(queueCapacity);
    executor.setKeepAliveSeconds(keepAliveSeconds);
    executor.setThreadNamePrefix("my-thread-pool-03");
    // 當(dāng)線程池已滿,且等待隊(duì)列也滿了的時(shí)候,拋棄一個(gè)在等待隊(duì)列中等待的時(shí)間最久的線程,并將當(dāng)前線程放入等待隊(duì)列(不會(huì)拋出異常)
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
    executor.initialize();
    return executor;
  }

  @Bean
  public Executor testMyThreadPool04() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setQueueCapacity(queueCapacity);
    executor.setKeepAliveSeconds(keepAliveSeconds);
    executor.setThreadNamePrefix("my-thread-pool-04");
    // 當(dāng)線程池已滿,且等待隊(duì)列也滿了的時(shí)候,直接拋棄當(dāng)前線程(不會(huì)拋出異常)
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
    executor.initialize();
    return executor;
  }
}

使用線程池

package org.pzy.spring.complex.bean;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TestService {

  @Async("testMyThreadPool01")
  public void say(int id) throws InterruptedException {
    System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId() + " --> " + id);
    Thread.sleep(2 * 1000);
  }

  @Async("testMyThreadPool02")
  public void say02(int id) throws InterruptedException {
    System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId() + " --> " + id);
    Thread.sleep(2 * 1000);
  }

  @Async("testMyThreadPool03")
  public void say03(int id) throws InterruptedException {
    System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId() + " --> " + id);
    Thread.sleep(2 * 1000);
  }

  @Async("testMyThreadPool04")
  public void say04(int id) throws InterruptedException {
    System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getId() + " --> " + id);
    Thread.sleep(2 * 1000);
  }
}

測(cè)試類

package org.pzy.spring.complex;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.pzy.spring.complex.bean.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTest {

  @Autowired
  private TestService testService;

  @Test
  public void test() throws InterruptedException {
    for (int i = 0; i < 10; i++) {
      testService.say(i);
    }
    Thread.sleep(10000 * 1000);
  }

  @Test
  public void test02() throws InterruptedException {
    for (int i = 0; i < 10; i++) {
      testService.say02(i);
    }
    Thread.sleep(10000 * 1000);
  }
  
  @Test
  public void test03() throws InterruptedException {
    for (int i = 0; i < 10; i++) {
      testService.say03(i);
    }
    Thread.sleep(10000 * 1000);
  }
  
  @Test
  public void test04() throws InterruptedException {
    for (int i = 0; i < 10; i++) {
      testService.say04(i);
    }
    Thread.sleep(10000 * 1000);
  }
}

配置文件

server:
  port: 56000
myThreadPool:
  corePoolSize: 1   # 核心線程池大小
  maxPoolSize: 3    # 最大線程池大小
  queueCapacity: 2  # 等待隊(duì)列大小
  keepAliveSeconds: 3 # 空閑線程存活時(shí)間

啟動(dòng)類

package org.pzy.spring.complex;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync //啟用異步編程
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class);
  }
}

代碼詳見(jiàn): https://gitee.com/free_pan/spring-summary/tree/master/spring-complex-04

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末叫胁,一起剝皮案震驚了整個(gè)濱河市凰慈,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌曹抬,老刑警劉巖溉瓶,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異谤民,居然都是意外死亡堰酿,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門张足,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)触创,“玉大人,你說(shuō)我怎么就攤上這事为牍『甙螅” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵碉咆,是天一觀的道長(zhǎng)抖韩。 經(jīng)常有香客問(wèn)我,道長(zhǎng)疫铜,這世上最難降的妖魔是什么茂浮? 我笑而不...
    開(kāi)封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮壳咕,結(jié)果婚禮上席揽,老公的妹妹穿的比我還像新娘。我一直安慰自己谓厘,他們只是感情好幌羞,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著竟稳,像睡著了一般属桦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上住练,一...
    開(kāi)封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天地啰,我揣著相機(jī)與錄音,去河邊找鬼讲逛。 笑死亏吝,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的盏混。 我是一名探鬼主播蔚鸥,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼惜论,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了止喷?” 一聲冷哼從身側(cè)響起馆类,我...
    開(kāi)封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎弹谁,沒(méi)想到半個(gè)月后乾巧,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡预愤,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年沟于,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片植康。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡旷太,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出销睁,到底是詐尸還是另有隱情供璧,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布冻记,位于F島的核電站睡毒,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏冗栗。R本人自食惡果不足惜吕嘀,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望贞瞒。 院中可真熱鬧,春花似錦趁曼、人聲如沸军浆。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)乒融。三九已至,卻和暖如春摄悯,著一層夾襖步出監(jiān)牢的瞬間赞季,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工奢驯, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留申钩,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓瘪阁,卻偏偏與公主長(zhǎng)得像撒遣,于是被迫代替她去往敵國(guó)和親邮偎。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容