步骤一:
线程池初始化类:
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPool {
public static ThreadPoolExecutor executor;
public ThreadPool() {
}
public static void endServer(ThreadPoolExecutor executor) {
executor.shutdown();
}
public void start() {
System.out.println("开启线程池...");
executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(5);
System.out.println("创建完成...");
}
}
步骤二:
具体的线程任务:
public class ThreadPoolTask implements Runnable {
private String name;
public ThreadPoolTask(String name) {
super();
this.name = name;
}
@Override
public void run() { //线程具体执行的任务
excuteMethod();
}
private void excuteMethod() {
for(int i = 0; i < 10; i++){
System.out.println(name + i);
}
}
}
步骤三:
操作线程类:
import java.util.concurrent.ThreadPoolExecutor;
import com.wonders.cop.atm.threadPool.start.ThreadPool;
import com.wonders.cop.atm.threadPool.task.ThreadPoolTask;
public class TereadPollTest {
/**
* 线程操作基本类
* @param services
* @param contentParameter
*/
public static void basicOperation(String name) {
try {
ThreadPoolExecutor executor = ThreadPool.executor;
if(executor != null) {
//创建任务
ThreadPoolTask threadPool = new ThreadPoolTask(name);
//执行任务
executor.execute(threadPool);
} else {
System.out.println("线程池没有创建!");
}
} catch (Exception e) {
System.out.println("异步操作异常!");
e.printStackTrace();
}
}
}
步骤四:
在项目启动的时候初始化线程池:
在springmvc中添加配置:
<!-- 设置随Spring启动的线程池 -->
<bean id="threadStart" class="com.wonders.cop.health.threadPool.start.ThreadPool"
init-method="start" />
<bean id="threatStart" class="类路径" init-method="start(线程池初始化类中的初始化方法名)"/>
PS:
main方法测试的话可以直接调用线程池初始化类中的初始化方法(步骤一),然后再调用线程操作类(步骤三)。
public static void main(String[] args) {
new ThreadPool().start();
String name1 = "线程A";
String name2 = "线程B------>";
String name3 = "线程C================";
TereadPollTest.basicOperation(name1);
TereadPollTest.basicOperation(name2);
TereadPollTest.basicOperation(name3);
}