zoukankan      html  css  js  c++  java
  • Java ThreadPoolTaskExecutor使用

    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");
    	}
    
    }
    

      

    参考

  • 相关阅读:
    Divide Two Integers
    LRU Cache
    Max Points on a Line
    Recover Binary Search Tree
    Copy List with Random Pointer
    IEE修改最大连接数
    SQL Tuning 基础概述02
    RHEL 本地yum源配置
    Linux演示 dd测试IO
    Linux平台oracle 11g单实例 安装部署配置 快速参考
  • 原文地址:https://www.cnblogs.com/linlf03/p/6511062.html
Copyright © 2011-2022 走看看