Spring和Java线程示例

Java thread images

这里有3个示例,向您展示如何在Spring中进行“ 线程化 ”。 请参阅代码以进行自我解释。

1. Spring + Java Threads示例

通过扩展Thread创建一个简单的Java线程,并由Spring的容器通过@Component 。 bean范围必须是“ prototype ”,以便每个请求将返回一个新实例,以运行每个单独的线程。

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

输出–顺序每次都不同,这是线程🙂

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非托管Bean示例

使用Spring的ThreadPoolTaskExecutor创建线程池。 Spring容器不必管理执行线程。

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

    }
}

输出–每次的顺序都会有所不同。

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线程池+ Spring托管Bean示例

这个示例再次使用ThreadPoolTaskExecutor ,并通过@Component将线程声明为Spring托管bean。

下面的PrintTask2是Spring托管的bean,您可以轻松地@Autowired任何必需的bean。

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

输出–每次的顺序都会有所不同。

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

喜欢您的意见,以改善上述程序。

下载源代码

下载它– Spring-Thread-Example.zip (22 KB)

参考文献

  1. Spring调度参考
  2. ThreadPoolTask​​Executor JavaDoc
  3. 在Spring配置文件中声明bean
  4. 如何关闭Spring任务执行程序/调度程序池
  5. Spring并发示例

翻译自: https://mkyong.com/spring/spring-and-java-thread-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值