1. 配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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"> <bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean> </beans>
2. 使用
public class App {
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Config.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.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")); //check active thread, if zero then shut down the thread pool
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;
}
} }
}
3. 线程
public class PrintTask implements Runnable{ String name; public PrintTask(String name){
this.name = name;
} @Override
public void run() { System.out.println(name + " is running"); try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println(name + " is running");
} }