Spring線程池開發實戰

Spring線程池開發實戰

原文出處:點擊打開鏈接

作者:chszs,轉載需註明。

作者博客主頁:http://blog.csdn.net/chszs

本文提供了三個Spring多線程開發的例子,由淺入深,由於例子一目瞭然,所以並未做過多的解釋。諸位一看便知。

前提條件:

1)在Eclipse創建一個Java項目,我取名爲SpringThreadDemo。
2)項目所需的JAR包如圖所示:
 

下面開始。


注:項目源碼已經託管到GitHub,地址:https://github.com/chszs/SpringThreadDemo

例子1:Spring結合Java線程。

通過繼承Thread創建一個簡單的Java線程,然後使用@Component讓spring容器管理此線程,Bean的範圍必須是prototype,因此每個請求都會返回一個新實例,運行每個單獨的線程。

PrintThread.java

[java] view plain copy
 print?
  1. package com.chszs.thread;  
  2.   
  3. import org.springframework.stereotype.Component;  
  4. import org.springframework.context.annotation.Scope;  
  5.   
  6. @Component  
  7. @Scope("prototype")  
  8. public class PrintThread extends Thread{  
  9.         @Override  
  10.         public void run(){  
  11.                 System.out.println(getName() + " is running.");  
  12.                 try{  
  13.                         Thread.sleep(5000);  
  14.                 }catch(InterruptedException e){  
  15.                         e.printStackTrace();  
  16.                 }  
  17.                 System.out.println(getName() + " is running again.");  
  18.         }  
  19. }  

AppConfig.java

[java] view plain copy
 print?
  1. package com.chszs.config;  
  2.   
  3. import org.springframework.context.annotation.ComponentScan;  
  4. import org.springframework.context.annotation.Configuration;  
  5.   
  6. @Configuration  
  7. @ComponentScan(basePackages="com.chszs.thread")  
  8. public class AppConfig {  
  9. }  

App.java

[java] view plain copy
 print?
  1. package com.chszs;  
  2. import org.springframework.context.ApplicationContext;  
  3. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  4.   
  5. import com.chszs.config.AppConfig;  
  6. import com.chszs.thread.PrintThread;  
  7.   
  8. public class App {  
  9.         public static void main(String[] args){  
  10.                 ApplicationContext ctx =   
  11.             new AnnotationConfigApplicationContext(AppConfig.class);  
  12.                 PrintThread printThread1 = (PrintThread)ctx.getBean("printThread");  
  13.                 printThread1.setName("Thread 1");  
  14.                   
  15.                 PrintThread printThread2 = (PrintThread)ctx.getBean("printThread");  
  16.                 printThread2.setName("Thread 2");  
  17.                   
  18.                 PrintThread printThread3 = (PrintThread)ctx.getBean("printThread");  
  19.                 printThread3.setName("Thread 3");  
  20.                   
  21.                 PrintThread printThread4 = (PrintThread)ctx.getBean("printThread");  
  22.                 printThread4.setName("Thread 4");  
  23.                   
  24.                 PrintThread printThread5 = (PrintThread)ctx.getBean("printThread");  
  25.                 printThread5.setName("Thread 5");  
  26.                   
  27.                 printThread1.start();  
  28.                 printThread2.start();  
  29.                 printThread3.start();  
  30.                 printThread4.start();  
  31.                 printThread5.start();  
  32.         }  
  33. }  

輸出:

Thread 1 is running.
Thread 2 is running.
Thread 4 is running.
Thread 5 is running.
Thread 3 is running.
Thread 2 is running again.
Thread 1 is running again.
Thread 5 is running again.
Thread 4 is running again.
Thread 3 is running again.


例子2:Spring線程池結合非Spring託管Bean。

使用Spring的ThreadPoolTaskExecutor類創建一個線程池。執行線程無需受Spring容器的管理。

PrintTask.java

[java] view plain copy
 print?
  1. package com.chszs.thread;  
  2.   
  3. public class PrintTask implements Runnable{  
  4.         String name;  
  5.         public PrintTask(String name){  
  6.                 this.name = name;  
  7.         }  
  8.         @Override  
  9.         public void run() {  
  10.                 System.out.println(name + " is running.");  
  11.                 try{  
  12.                         Thread.sleep(5000);  
  13.                 }catch(InterruptedException e){  
  14.                         e.printStackTrace();  
  15.                 }  
  16.                 System.out.println(name + " is running again.");  
  17.         }  
  18.           
  19. }  

Spring-Config.xml

[html] view plain copy
 print?
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3.         xmlns:context="http://www.springframework.org/schema/context"  
  4.         xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd">  
  8.           
  9.         <bean id="taskExecutor"   
  10.         class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
  11.                 <property name="corePoolSize" value="5" />  
  12.                 <property name="maxPoolSize" value="10" />  
  13.                 <property name="WaitForTasksToCompleteOnShutdown" value="true" />  
  14.         </bean>  
  15. </beans>  

注意這個Spring配置文件的位置,如圖所示:



App1.java

[java] view plain copy
 print?
  1. package com.chszs;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  6.   
  7. import com.chszs.thread.PrintTask;  
  8.   
  9. public class App1 {  
  10.   
  11.         public static void main(String[] args) {  
  12.                 ApplicationContext ctx =   
  13.             new ClassPathXmlApplicationContext("resources/Spring-Config.xml");  
  14.                 ThreadPoolTaskExecutor taskExecutor =  
  15.             (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");  
  16.                 taskExecutor.execute(new PrintTask("Thread 1"));  
  17.                 taskExecutor.execute(new PrintTask("Thread 2"));  
  18.                 taskExecutor.execute(new PrintTask("Thread 3"));  
  19.                 taskExecutor.execute(new PrintTask("Thread 4"));  
  20.                 taskExecutor.execute(new PrintTask("Thread 5"));  
  21.                 // 檢查活動的線程,如果活動線程數爲0則關閉線程池  
  22.                 for(;;){  
  23.                         int count = taskExecutor.getActiveCount();  
  24.                         System.out.println("Active Threads : " + count);  
  25.                         try{  
  26.                                 Thread.sleep(1000);  
  27.                         }catch(InterruptedException e){  
  28.                                 e.printStackTrace();  
  29.                         }  
  30.                         if(count==0){  
  31.                                 taskExecutor.shutdown();  
  32.                                 break;  
  33.                         }  
  34.                 }  
  35.         }  
  36.   
  37. }  

輸出:

Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
Thread 4 is running.
Active Threads : 4
Thread 5 is running.
Active Threads : 5
Active Threads : 5
Active Threads : 5
Active Threads : 5
Active Threads : 5
Thread 4 is running again.
Thread 2 is running again.
Thread 3 is running again.
Thread 1 is running again.
Thread 5 is running again.
Active Threads : 0

作者:chszs,轉載需註明。博客主頁:http://blog.csdn.NET/chszs

例子3:Spring線程池結合Spring託管Bean。


本例仍然使用ThreadPoolTaskExecutor類,並使用@Component註釋聲明Spring的託管Bean。
下面的例子PrintTask2是Spring的託管Bean,使用@Autowired註釋簡化代碼。

PrintTask2.java

[java] view plain copy
 print?
  1. package com.chszs.thread;  
  2.   
  3. import org.springframework.context.annotation.Scope;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. @Component  
  7. @Scope("prototype")  
  8. public class PrintTask2 implements Runnable {  
  9.         String name;  
  10.   
  11.         public void setName(String name) {  
  12.                 this.name = name;  
  13.         }  
  14.           
  15.         @Override  
  16.         public void run(){  
  17.                 System.out.println(name + " is running.");  
  18.                 try{  
  19.                         Thread.sleep(5000);  
  20.                 }catch(InterruptedException e){  
  21.                         e.printStackTrace();  
  22.                 }  
  23.                 System.out.println(name + " is running again.");  
  24.         }  
  25. }  

AppConfig.java

[java] view plain copy
 print?
  1. package com.chszs.config;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.ComponentScan;  
  5. import org.springframework.context.annotation.Configuration;  
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  7.   
  8. @Configuration  
  9. @ComponentScan(basePackages="com.chszs.thread")  
  10. public class AppConfig {  
  11.         @Bean  
  12.         public ThreadPoolTaskExecutor taskExecutor(){  
  13.                 ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();  
  14.                 pool.setCorePoolSize(5);  
  15.                 pool.setMaxPoolSize(10);  
  16.                 pool.setWaitForTasksToCompleteOnShutdown(true);  
  17.                 return pool;  
  18.         }  
  19. }  

App2.java

[java] view plain copy
 print?
  1. package com.chszs;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  6.   
  7. import com.chszs.config.AppConfig;  
  8. import com.chszs.thread.PrintTask2;  
  9.   
  10. public class App2 {  
  11.         public static void main(String[] args) {  
  12.                 ApplicationContext ctx =   
  13.             new AnnotationConfigApplicationContext(AppConfig.class);  
  14.                 ThreadPoolTaskExecutor taskExecutor =  
  15.             (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");  
  16.                   
  17.                 PrintTask2 printTask1 = (PrintTask2)ctx.getBean("printTask2");  
  18.                 printTask1.setName("Thread 1");  
  19.                 taskExecutor.execute(printTask1);  
  20.                   
  21.                 PrintTask2 printTask2 = (PrintTask2)ctx.getBean("printTask2");  
  22.                 printTask2.setName("Thread 2");  
  23.                 taskExecutor.execute(printTask2);  
  24.                   
  25.                 PrintTask2 printTask3 = (PrintTask2)ctx.getBean("printTask2");  
  26.                 printTask3.setName("Thread 3");  
  27.                 taskExecutor.execute(printTask3);  
  28.                   
  29.                 for(;;){  
  30.                         int count = taskExecutor.getActiveCount();  
  31.                         System.out.println("Active Threads : " + count);  
  32.                         try{  
  33.                                 Thread.sleep(1000);  
  34.                         }catch(InterruptedException e){  
  35.                                 e.printStackTrace();  
  36.                         }  
  37.                         if(count==0){  
  38.                                 taskExecutor.shutdown();  
  39.                                 break;  
  40.                         }  
  41.                 }  
  42.         }  
  43.   
  44. }  

輸出:

Thread 1 is running.
Thread 2 is running.
Active Threads : 2
Thread 3 is running.
Active Threads : 3
Active Threads : 3
Active Threads : 3
Active Threads : 3
Thread 1 is running again.
Thread 2 is running again.
Thread 3 is running again.
Active Threads : 1
Active Threads : 0

從這三個簡單的實例中,你是不是發現了Spring框架在多線程方面的強大之處!!

發佈了20 篇原創文章 · 獲贊 24 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章