如何在JAVA中創建線程池

ExecutorService

今天小編要分享的是關於線程池,

想必接觸到併發處理的朋友都有用到線程池,

當我們訪問服務器的量達到服務器一定量的時候,

比如幾百萬幾千萬,很容易造成服務器崩掉,

如果使用線程進行併發處理,將使用的線程進行回收在使用,就減小了服務器的壓力

下面寫一個例子介紹線程池的使用方法:


package com.dstech.market.service.impl;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.dstech.dssp.base.annotation.MethodParameter;
import com.dstech.dssp.comp.bomf.manager.BomfManager;
import com.dstech.dssp.service.BasicBeanService;
import com.dstech.market.bean.DsDocInfo;
import com.dstech.market.service.DsDocInfoService;

/**
* DsDocInfoServiceImpl.java
*/
@Component("marketDsDocInfoService")
@DependsOn({"bomfManager"})
public class DsDocInfoServiceImpl  extends BasicBeanService<DsDocInfo> implements DsDocInfoService {
	//log
private static Logger log=LoggerFactory.getLogger(DsDocInfoServiceImpl.class);
//創建線程池
private static  ExecutorService newCachedThreadPool =newFixedThreadPool1(10);
//wx7e3c48ae7772ee10  wx3f465fb88215de20
@Override
public Class<?> getType() {
	return DsDocInfoService.class;
}

/**
 * 初始化
 */
@PostConstruct
public void init(){
	BomfManager.getInstance().addApi(this);
}

/**
 * 查詢
 */
@Override
@MethodParameter(desc="DsInfoQuery", input="Id",postType={},postName="",queryString="",httpMethod="get")
public List<DsDocInfo> DsInfoQuery(String Id) throws Exception {
	List<DsDocInfo> dicInfo=this.getBeanDaoHelper().queryWhere(DsDocInfo.class, "doc_id=?", new Object[]{Id}, null);
	return dicInfo;	
}


/**
 * 線程池
 * newCachedThreadPool創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閒線程,若無可回收,則新建線程; 
 * newFixedThreadPool 創建一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待; 
 * newScheduledThreadPool 創建一個定長線程池,支持定時及週期性任務執行; 
 * newSingleThreadExecutor 創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行; 
 **/			 
@Override
@MethodParameter(desc="dsquery", input="Id",postType={},postName="",queryString="",httpMethod="get")
public List<DsDocInfo> dsquery(final String Id) throws Exception {
	
	for (int i = 0; i <20; i++){
        newCachedThreadPool.execute(new Runnable(){
            public void run() {
                try {
                    System.out.println("線程名稱爲:"+Thread.currentThread().getName());
                    System.out.println("線程Id爲:"+Thread.currentThread().getId());
                    //休眠時間0.2秒
                    Thread.sleep(200);
                    try {
                    	//調用查詢方法
                    	List<DsDocInfo> list=DsInfoQuery(Id);
                    	if(list!=null&&list.size()>0){
                    		for (DsDocInfo dsDocInfo : list) {
								System.out.println("文檔Id:"+dsDocInfo.getDocId()+"\t創建人:"+dsDocInfo.getCreatePerson());
							}
                    	}
					} catch(Exception e){
						//TODO Auto-generated catch block
						e.printStackTrace();
					}
                } catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
    }
	return null;
}

/**
 * 以下是對線程池的設置
  * @Title: newCachedThreadPool 
  * @Description: TODO
  * @param @param nThreads
  * @param @return 
  * @return ExecutorService
  * @throws
 */
public static ExecutorService newCachedThreadPool(int nThreads){
	//5:核心池大小,	5:最大池大小,60L:保活時間,SECONDS秒
	//return new ThreadPoolExecutor(nThreads,nThreads, 60L,TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
	return new ThreadPoolExecutor(nThreads,Integer.MAX_VALUE,1L,TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
public static ExecutorService newFixedThreadPool(int nThreads){  
	//nThreads核心池大小 ,nThreads最大池大小,0L,保活時間,MILLISECOND毫秒
		return new ThreadPoolExecutor(nThreads,nThreads,0L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
	}
	
public static ExecutorService newFixedThreadPool1(int nThreads){
	return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>());
}

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory){
	return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>(), threadFactory);
}

}

好啦,今天的分享就到這裏喔!

記得點一個贊哦,你的贊是小編成功的第一步

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章