Java线程池 ExecutorService( [ɪgˈzekjətə(r)] ) 的运用

一,线程池工具类

package demo.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 线程池工具类(单例模式)
 * @author xiaohui
 *
 */
public class ThreadPoolUtil {
	
	private ThreadPoolUtil() {}

	private static ExecutorService thread = null;
	
	public static ExecutorService get() {
		if(thread==null) {
			//设置固定数量的线程数量,超出的线程会在列队外等待
			thread = Executors.newFixedThreadPool(6);
		}
		return thread;
	}
	
}

二,业务类

package demo.service;

/**
 * 测试业务类
 * @author xiaohui
 *
 */
public class TestService {

	public void test(String name) {
		System.out.println("hello " + name);
	}
	
}

三,线程类

package demo.service;

import java.util.concurrent.TimeUnit;

/**
 * 测试线程类
 * @author xiaohui
 *
 */
public class TestThread implements Runnable{
	
	//要执行的方法的参数
	private String name;
	//要执行的业务类对象
	private TestService testService;
	
	//构造方法
	public TestThread(String name,TestService testService) {
		this.name = name;
		this.testService=testService;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		testService.test(name);
		//使线程睡眠,模拟线程阻塞情况
		try {
		   TimeUnit.SECONDS.sleep(5);
		}catch (InterruptedException e) {
		   e.printStackTrace();
		} 
	}

}

四,运行

package demo.test;

import java.util.concurrent.ExecutorService;

import demo.service.TestService;
import demo.service.TestThread;
import demo.util.ThreadPoolUtil;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//从线程池中获取一个线程
		ExecutorService thread = ThreadPoolUtil.get();
		for(int i=0;i<100;i++) {
			//执行线程
			thread.execute(new TestThread(i+"",new TestService()));
		}
		//执行完后关闭线程
		thread.shutdown();
	}

}

五,运行结果

5秒后

六,结论

1, Executors.newFixedThreadPool(6);设置的线程数是固定的,最大为6个线程,超出的线程会等待其它线程空闲时再执行。

2,可以避免内存溢出。

七,代码案例 

项目案例(码云)

八,其它参考

Java线程池(ExecutorService)使用