1. 程式人生 > >Java執行緒池 ExecutorService( [ɪgˈzekjətə(r)] ) 的運用

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,可以避免記憶體溢位。

七,程式碼案例 

八,其它參考