`
heipark
  • 浏览: 2094670 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

实现spring + java多线程(转)

    博客分类:
  • Java
 
阅读更多

转自:http://www.mkyong.com/spring/spring-and-java-thread-example/

 

1. Spring + Java Threads example

Create a simple Java thread by extending Thread, and managed by Spring’s container via @Component. The bean scope must be “prototype“, so that each request will return a new instance, to run each individual thread.

PrintThread.java
package com.mkyong.thread;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
@Component
@Scope("prototype")
public class PrintThread extends Thread{
 
	@Override
	public void run() {
 
		System.out.println(getName() + " is running");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(getName() + " is running");
	}
 
}
AppConfig.java
package com.mkyong.config;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ComponentScan(basePackages="com.mkyong.thread")
public class AppConfig{
}
App.java
package com.mkyong;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
import com.mkyong.config.AppConfig;
import com.mkyong.thread.PrintThread;
 
public class App 
{
    public static void main( String[] args )
    {
 
    	ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
 
    	PrintThread printThread1 = (PrintThread) ctx.getBean("printThread");
    	printThread1.setName("Thread 1");
 
    	PrintThread printThread2 = (PrintThread) ctx.getBean("printThread");
    	printThread2.setName("Thread 2");
 
    	PrintThread printThread3 = (PrintThread) ctx.getBean("printThread");
    	printThread3.setName("Thread 3");
 
    	PrintThread printThread4 = (PrintThread) ctx.getBean("printThread");
    	printThread4.setName("Thread 4");
 
    	PrintThread printThread5 = (PrintThread) ctx.getBean("printThread");
    	printThread5.setName("Thread 5");
 
    	printThread1.start();
    	printThread2.start();
    	printThread3.start();
    	printThread4.start();
    	printThread5.start();
 
    }
}

Output – The order will be vary each time, this is thread :)

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

2. Spring Thread Pool + Spring non-managed bean example

Uses Spring’s ThreadPoolTaskExecutor to create a thread pool. The executing thread is not necessary managed by Spring container.

PrintThread.java – This thread is not managed by Spring, NO @Component
package com.mkyong.thread;
 
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");
	}
 
}
Spring-Config.xml – ThreadPoolTaskExecutor in XML file
<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>
App.java
package com.mkyong;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import com.mkyong.thread.PrintTask;
 
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;
		}
	}
 
    }
}

Output – The order will be vary each time.

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
Thread 2 is running
Thread 1 is running
Thread 3 is running
Thread 4 is running
Thread 5 is running
Active Threads : 0

3. Spring Thread Pool + Spring managed bean example

This example is using ThreadPoolTaskExecutor again, and declares the thread as Spring managed bean via @Component.

The below PrintTask2 is Spring managed bean, you can @Autowired any required beans easily.

PrintTask2.java
package com.mkyong.thread;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{
 
	String name;
 
	public void setName(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");
 
	}
 
}
AppConfig.java – ThreadPoolTaskExecutor in Spring configuration file
package com.mkyong.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
@Configuration
@ComponentScan(basePackages = "com.mkyong.thread")
public class AppConfig {
 
	@Bean
	public ThreadPoolTaskExecutor taskExecutor() {
		ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
		pool.setCorePoolSize(5);
		pool.setMaxPoolSize(10);
		pool.setWaitForTasksToCompleteOnShutdown(true);
		return pool;
	}
 
}
App.java
package com.mkyong;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import com.mkyong.config.AppConfig;
import com.mkyong.thread.PrintTask2;
 
public class App {
  public static void main(String[] args) {
 
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
 
    PrintTask2 printTask1 = (PrintTask2) context.getBean("printTask2");
    printTask1.setName("Thread 1");
    taskExecutor.execute(printTask1);
 
    PrintTask2 printTask2 = (PrintTask2) context.getBean("printTask2");
    printTask2.setName("Thread 2");
    taskExecutor.execute(printTask2);
 
    PrintTask2 printTask3 = (PrintTask2) context.getBean("printTask2");
    printTask3.setName("Thread 3");
    taskExecutor.execute(printTask3);
 
	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;
		}
	}
 
   }
}

Output – The order will be vary each time.

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

Love your comment to improve above program.

分享到:
评论

相关推荐

    JAVA零基础到高级进阶特训营 JAVA多线程并发设计+Spring高级+数据库开发+JAVA基础等

    这套课程既可以作为从零基础开始...课程的主要内容涉及有JAVA基础课程、JAVA多线程与并发编程、数据库开发基础和进阶、Spring Framework、Spring进阶、Spring MVC框架、Spring boot、Java常用类库、Java异常处理等等

    java中spring里实现多线程

    在Java编程中,Spring框架是企业级应用开发的首选,...总之,Spring通过提供高级的线程管理和调度工具,简化了在Java应用程序中实现多线程的复杂性。理解并熟练使用这些工具,能帮助开发者编写出高效、健壮的并发程序。

    spring boot注解事务+多线程

    本示例将深入探讨如何使用注解来实现事务控制以及如何在Spring Boot中运用多线程。 首先,让我们关注"注解事务"。在Spring框架中,我们主要依赖`@Transactional`注解来声明事务边界。当一个方法被这个注解标记时,...

    Spring+DHTML+js+java API大汇总

    Java API涵盖了基础类型、集合框架、网络编程、多线程、I/O流等多个方面,是Java开发者不可或缺的资源。在构建Web服务时,Java API如JAX-RS(Java API for RESTful Web Services)用于创建RESTful API,使得服务可以...

    基于Spring+Ibatis的安全线程实现

    4. **线程池管理**:Spring提供ThreadPoolTaskExecutor,我们可以自定义线程池配置,比如核心线程数、最大线程数、队列长度等,以优化多线程执行效率,并通过设置RejectedExecutionHandler处理拒绝策略。 5. **事务...

    openCv+java+spring boot

    Java的多线程能力使得处理多个并发请求成为可能,提高了系统的响应速度。 Spring Boot简化了Spring框架的使用,允许快速开发和部署微服务。在这个项目中,Spring Boot可以用于创建RESTful API,提供人脸检测和识别...

    java多线程处理数据库数据

    本主题将深入探讨如何使用Java的并发包(java.util.concurrent)来实现多线程对数据库数据的批量处理,包括增、删、改等操作。 首先,我们需要了解Java中的线程基础。线程是程序执行的最小单位,一个进程可以包含多...

    java多线程程序设计:Java NIO+多线程实现聊天室

    java多线程程序设计:Java NIO+多线程实现聊天室 Java基于多线程和NIO实现聊天室 涉及到的技术点 线程池ThreadPoolExecutor 阻塞队列BlockingQueue,生产者消费者模式 Selector Channel ByteBuffer ProtoStuff 高...

    spring4+junit4.8 +多线程TheadTool

    3. **多线程(TheadTool)**:在Java中,我们可以使用`java.lang.Thread`类来创建和管理线程,但实际开发中可能会遇到一些复杂情况,如线程同步、线程池管理等。TheadTool可能是自定义的工具类,用于简化多线程编程...

    java多线程导出excel(千万级别)优化

    Java多线程导出Excel是处理大数据量时的一种高效策略,尤其在面对千万级别的数据时。传统的Apache POI库在处理大规模数据时可能会遇到栈溢出(StackOverflowError)和内存溢出(OutOfMemoryError)等问题,因为这些...

    java 网盘源码 struts+spring+hibernate

    "Java网盘源码:Struts+Spring+Hibernate"是一个典型的企业级项目,它利用了Java语言的三大框架——Struts、Spring和Hibernate,实现了高效且灵活的数据管理与业务逻辑处理。下面将详细解析这个项目中的关键技术和...

    HttpClient+ Spring实现多线程

    标题 "HttpClient + Spring 实现多...为了实现多线程,可以使用Spring的ThreadPoolTaskExecutor或者Java内置的ExecutorService。例如,在`applicationContext-quartz.xml`配置文件中,可能会定义一个线程池: ```xml ...

    Java多线程之定时任务 以及 SpringBoot多线程实现定时任务——异步任务

    1. SpringBoot 自定义线程池以及多线程间的异步调用(@Async、@EnableAsync) 2.Java多线程之定时任务 以及 SpringBoot多线程实现定时任务 3.@EnableScheduling 与 @Scheduled

    Spring的多线程应用

    在【描述】中提到的"一个简单的spring的多线程demo",我们可以理解为一个示例项目,旨在帮助开发者理解如何在Spring中实现和管理多线程。 在Java中,多线程主要用于提高应用程序的执行效率,尤其是在处理I/O密集型...

    基于SpringBoot和POI实现单线程和多线程导出Excel.zip

    基于SpringBoot和POI实现单线程和多线程导出Excel.zip基于SpringBoot和POI实现单线程和多线程导出Excel.zip基于SpringBoot和POI实现单线程和多线程导出Excel.zip基于SpringBoot和POI实现单线程和多线程导出Excel.zip...

    Struts+Spring+Hibernate_upload_and_download.rar_Spring+Hibernate

    例如,限制文件大小防止DoS攻击,使用多线程处理大文件上传以提高效率,以及对上传文件进行病毒扫描等。在实际应用中,可能还需要考虑文件版本控制、权限管理、存储策略(如云存储集成)等问题。 综上所述,...

    java简单分布式架构,多个数据源,线程池多线程访问

    综上所述,这个项目涉及到的知识点包括:分布式系统设计、Java多线程与线程池、Spring框架的多数据源支持、MyBatis的使用以及Spring的事务管理。通过这些技术的组合,可以构建出一个高效、可扩展的分布式应用,以...

Global site tag (gtag.js) - Google Analytics