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

      

    参考

  • 相关阅读:
    linux系统安装mysql数据库
    laypage分页控件使用方法
    could not get wglGetExtensionsStringARB
    Eclipse -- 自动补齐设置和其他用法
    Android开发--AndroidManifest.xml文件解析
    Java--常识
    课题论文写作时思路---目前存在的不足
    课题论文之调研---已有研究算法概述
    课题论文之调研---脏腑辨证
    Bayesian 网络分类算法
  • 原文地址:https://www.cnblogs.com/linlf03/p/6511062.html
Copyright © 2020-2023  润新知