---
title: "线程池"
author: "rainyear"
date: "2011-09-28T11:51:58Z"
tags: []
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2012-03-06T16:24:40Z"
id: 1182310
url: "https://rainyear.iteye.com/blog/1182310"
---

最近业务需求，需要导出大量数据到Excel文档中。
1>Action文件	 
			//ExecutorService pool = Executors.newSingleThreadExecutor();
			// 记录日志  异步将导出的xls文件写到服务器的制定目录
			ExpProductThread thread = new ExpProductThread(new Long(0),this.getCommandContext().getUserId(),workbook,exportFileName);
			//thread.start(); 
			XiuECThreadPoolRegistry.getInstance().getThreadPool().execute(thread);
			//pool.execute(thread);
			//pool.shutdown();
			/*****add by sam.shi 2011-09-23*****/

2>线程：
package com.xiu.commerce.product.helpers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.ibm.commerce.ras.ECTrace;
import com.ibm.commerce.ras.ECTraceIdentifiers;
import com.xiu.commerce.helpers.XiuECApplicationConfigRegistry;
import com.xiu.commerce.log.beans.LogBean;
import com.xiu.commerce.log.beans.LogManager;
import com.xiu.commerce.log.helpers.ECLogMessage;
 public class ExpProductThread extends Thread
{
    /**
     * 操作名称
     */
    private String       atcion;

    /**
     * 操作日志
     */
    private String       stanceLog;

    /**
     * 操作日志内容
     */
    private String       note;

    /**
     * 用户ID
     */
    private Long         userId;

    /**
     * 业务ID
     */
    private Long         instanceId;

    /**
     * EXCEL操作对象
     */
    private HSSFWorkbook workbook;

    /**
     * EXCEL文件名称
     */
    private String       fileName;

    public ExpProductThread(Long instanceId, Long userId, HSSFWorkbook workbook, String fileName)
    {
        this.atcion = "导出EXCEL";
        this.stanceLog = "导出商品信息";
        this.note = "导出商品信息,导出的EXCEL文件路径为：";
        this.userId = userId;
        this.instanceId = instanceId;
        this.workbook = workbook;
        this.fileName = fileName;
    }

    public void run()
    {
        ECTrace.entry(ECTraceIdentifiers.COMPONENT_EXTERN, ExpProductThread.class.getName(), "run");
        StringBuffer sb = new StringBuffer(100);
        SimpleDateFormat df = new SimpleDateFormat(XiuECApplicationConfigRegistry.getInstance().getValue("ExpFile/formatStr"));
        String time = df.format(new java.util.Date());
        sb.append(XiuECApplicationConfigRegistry.getInstance().getValue("ExpFile/path"));
        sb.append(time);
        sb.append(File.separator);

        OutputStream out = null;
        try
        {
            File file = new File(sb.toString());
            if (!file.exists())
                file.mkdirs();
            out = new FileOutputStream(new File(sb.append(fileName).toString()));
            this.workbook.write(out);

            // 记录操作日志
            this.insertLog(atcion, stanceLog, note + sb.toString(), userId, instanceId);
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            ECTrace.trace(ECTraceIdentifiers.COMPONENT_EXTERN, ExpProductThread.class.getName(), "run", "出现异常："
                    + e.toString());
        }
        finally
        {
            try
            {
                if (null != out)
                    out.close();
            }
            catch (IOException e)
            {
                // TODO 自动生成 catch 块
                //e.printStackTrace();
            }

            ECTrace.exit(ECTraceIdentifiers.COMPONENT_EXTERN, ExpProductThread.class.getName(), "run");
        }
    }

    /**
     * 写操作日志
     * @param atcion 操作名称
     * @param stanceLog 操作日志
     * @param note 操作日志内容
     * @param userId 用户ID
     */
    private void insertLog(String atcion, String stanceLog, String note, Long userId, Long instanceId)
    {
        LogManager logManager = new LogManager();
        LogBean logBean = new LogBean();
        logBean.setEvenLevel(ECLogMessage.EVEN_LEVEL_INFO);// 级别等级：1:info,2:debug,3:error,(属性文件)
        logBean.setEvenSystem(ECLogMessage.EVEN_SYSTEM_STORE);// 在属性文件中配置，例如：1-商品中心
        logBean.setEvenModule(ECLogMessage.EVEN_MODULE_STORE);// 在属性文件里配置，例如：1：品牌管理，2：分类管理，3：商品信息，4：属性字典，5：价格管理，6：库存管理，7：上下架管理，8：档期列表
        logBean.setEvenAction(atcion);// 导出
        logBean.setEvenInstance(stanceLog); //导出
        logBean.setEvenNote(note);// 导出
        logBean.setEvenInstanceId(instanceId.toString());
        logBean.setEvenUserID(userId.intValue());//用户Id
        logManager.setLogData(logBean);
    }
}
3》线程池 在系统启动时会自动初始化线程池
public class XiuECThreadPoolRegistry implements Registry
{
    private static int                     poolSize = 3;

    private static ExecutorService         pool     = null;

    private static XiuECThreadPoolRegistry instance = null;

    public static XiuECThreadPoolRegistry getInstance()
    {
        if (instance == null)
        {
            instance = (XiuECThreadPoolRegistry) RegistryManager.singleton().getRegistry("XiuECThreadPoolRegistry");
        }
        return instance;
    }

    public ExecutorService getThreadPool()
    {
        if (null == pool)
        {
            String poolsize = XiuECApplicationConfigRegistry.getInstance().getValue("ThreadPool/size");
            if (!StringUtil.isEmpty(poolsize))
                pool = Executors.newFixedThreadPool(Integer.parseInt(poolsize));
            else
                pool = Executors.newFixedThreadPool(poolSize);
        }
        return pool;
    }

    @Override
    public void initialize() throws Exception
    {
        this.refresh();
    }

    @Override
    public void refresh() throws Exception
    {
        String methodName = "initialize";
        ECTrace.entry(ECTraceIdentifiers.COMPONENT_EXTERN, this.getClass().getName(), methodName);
        if (null == pool)
        {
            String poolsize = XiuECApplicationConfigRegistry.getInstance().getValue("ThreadPool/size");
            ECTrace.trace(ECTraceIdentifiers.COMPONENT_EXTERN, this.getClass().getName(), methodName, "线程池大小："
                    + poolsize);
            if (!StringUtil.isEmpty(poolsize))
                pool = Executors.newFixedThreadPool(Integer.parseInt(poolsize));
            else
                pool = Executors.newFixedThreadPool(poolSize);
        }
        ECTrace.exit(ECTraceIdentifiers.COMPONENT_EXTERN, this.getClass().getName(), methodName);
    }
}
转：
在Java5之后，并发线程这块发生了根本的变化，最重要的莫过于新的启动、调度、管理线程的一大堆API了。在Java5以后，通过Executor来启动线程比用Thread的start（）更好。在新特征中，可以很容易控制线程的启动、执行和关闭过程，还可以很容易使用线程池的特性。

　　一、创建任务

　　任务就是一个实现了Runnable接口的类。

　　创建的时候实run方法即可。

　　二、执行任务

　　通过java.util.concurrent.ExecutorService接口对象来执行任务，该接口对象通过工具类java.util.concurrent.Executors的静态方法来创建。

　　Executors此包中所定义的 Executor、ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 类的工厂和实用方法。

　　ExecutorService提供了管理终止的方法，以及可为跟踪一个或多个异步任务执行状况而生成 Future 的方法。 可以关闭 ExecutorService，这将导致其停止接受新任务。关闭后，执行程序将最后终止，这时没有任务在执行，也没有任务在等待执行，并且无法提交新任务。

　　executorService.execute（new TestRunnable（））；

　　1、创建ExecutorService

　　通过工具类java.util.concurrent.Executors的静态方法来创建。

　　Executors此包中所定义的 Executor、ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 类的工厂和实用方法。

　　比如，创建一个ExecutorService的实例，ExecutorService实际上是一个线程池的管理工具：

　　ExecutorService executorService = Executors.newCachedThreadPool（）；

　　ExecutorService executorService = Executors.newFixedThreadPool（3）；

　　ExecutorService executorService = Executors.newSingleThreadExecutor（）；

　　2、将任务添加到线程去执行

　　当将一个任务添加到线程池中的时候，线程池会为每个任务创建一个线程，该线程会在之后的某个时刻自动执行。

　　三、关闭执行服务对象

　　executorService.shutdown（）；

　　四、综合实例

package concurrent;

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors;

/** 
* Created by IntelliJ IDEA. 
* 
* @author leizhimin 2008-11-25 14:28:59 
*/ 
public class TestCachedThreadPool { 
        public static void main(String args) { 
//                ExecutorService executorService = Executors.newCachedThreadPool(); 
                ExecutorService executorService = Executors.newFixedThreadPool(5); //         ExecutorService executorService = Executors.newSingleThreadExecutor();

                for (int i = 0; i < 5; i++) { 
                        executorService.execute(new TestRunnable()); 
                        System.out.println("************* a" + i + " *************"); 
                } 
                executorService.shutdown(); 
        } 
}

class TestRunnable implements Runnable { 
        public void run() { 
                System.out.println(Thread.currentThread().getName() + "线程被调用了。"); 
                while (true) { 
                        try { 
                                Thread.sleep(5000); 
                                System.out.println(Thread.currentThread().getName()); 
                        } catch (InterruptedException e) { 
                                e.printStackTrace(); 
                        } 
                } 
        } 
}
Executors.newCachedThreadPool（）； //带缓存的 不够时自动添加Executors.newSingleThreadExecutor（）； //单个线程池 线程死掉后自动创建Executors.newFixedThreadPool（10）； //创建容纳N个线程的Executors.newScheduledThreadPool（19）； //创建定时器线程池

************* a0 ************* 
************* a1 ************* 
pool-1-thread-2线程被调用了。 
************* a2 ************* 
pool-1-thread-3线程被调用了。 
pool-1-thread-1线程被调用了。 
************* a3 ************* 
************* a4 ************* 
pool-1-thread-4线程被调用了。 
pool-1-thread-5线程被调用了。 
pool-1-thread-2 
pool-1-thread-1 
pool-1-thread-3 
pool-1-thread-5 
pool-1-thread-4 
pool-1-thread-2 
pool-1-thread-1 
pool-1-thread-3 
pool-1-thread-5 
pool-1-thread-4