}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name + " is running again.");
}
}
Spring-Config.xml
[html]
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
注意这个Spring配置文件的位置,如图所示:

App1.java
[java]
package com.chszs;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.chszs.thread.PrintTask;
public class App1 {
public static void main(String[] args) {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("resources/Spring-Config.xml");
ThreadPoolTaskExecutor taskExecutor =
(ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");
taskExecutor.execute(new PrintTask("Thread 1"));
taskExecutor.execute(new PrintTask("Thread 2"));
taskExecutor.execute(new PrintTask("Thread 3"));
taskExecutor.execute(new PrintTask("Thread 4"));
taskExecutor.execute(new PrintTask("Thread 5"));
// 检查活动的线程,如果活动线程数为0则关闭线程池
for(;;){
int count = taskExecutor.getActiveCount();
System.out.println("Active Threads : " + count);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
if(count==0){
taskExecutor.shutdown();
break;
}
}
}
}
输出:
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
例子3:Spring线程池结合Spring托管Bean。
本例仍然使用ThreadPoolTaskExecutor类,并使用@Component注释声明Spring的托管Bean。
下面的例子PrintTask2是Spring的托管Bean,使用@Autowired注释简化代码。
PrintTask2.java
[java]
package com.chszs.thread;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class PrintTask2 implements Runnable {
String name;
public void