java ThreadPoolUtil


import java.util.LinkedList;


public class ThreadPoolUtil extends ThreadGroup{

   private static final ThreadPoolUtil instance = new ThreadPoolUtil(5);
   
   private boolean isClosed = false;  //线程池是否关闭   
   private LinkedList workQueue;      //工作队列  
   private static int threadPoolID = 1;  //线程池的id  
   private ThreadPoolUtil(int poolSize) {  //poolSize 表示线程池中的工作线程的数量  
 
       super(threadPoolID + "");      //指定ThreadGroup的名称  
       setDaemon(true);               //继承到的方法,设置是否守护线程池  
       workQueue = new LinkedList();  //创建工作队列  
       for(int i = 0; i < poolSize; i++) {  
           new WorkThread(i).start();   //创建并启动工作线程,线程池数量是多少就创建多少个工作线程  
       }  
   }  
   
   public synchronized static ThreadPoolUtil getInstance(){
    return instance;
   }
     
   /** 向工作队列中加入一个新任务,由工作线程去执行该任务*/  
   public synchronized void execute(Runnable task) {  
        if(isClosed) {  
           throw new IllegalStateException();  
       }  
       if(task != null) {  
           workQueue.add(task);//向队列中加入一个任务  
           notify();           //唤醒一个正在getTask()方法中待任务的工作线程  
       }  
   }  
     
   /** 从工作队列中取出一个任务,工作线程会调用此方法*/  
   private synchronized Runnable getTask(int threadid) throws InterruptedException {  
       while(workQueue.size() == 0) {  
           if(isClosed) return null;  
           System.out.println("工作线程"+threadid+"等待任务...");  
           wait();             //如果工作队列中没有任务,就等待任务  
       }  
       System.out.println("工作线程"+threadid+"开始执行任务...");  
       return (Runnable) workQueue.removeFirst(); //反回队列中第一个元素,并从队列中删除  
   }  
     
   /** 关闭线程池 */  
   public synchronized void closePool() {  
       if(! isClosed) {  
           waitFinish();        //等待工作线程执行完毕  
           isClosed = true;  
           workQueue.clear();  //清空工作队列  
           interrupt();        //中断线程池中的所有的工作线程,此方法继承自ThreadGroup类  
       }  
   }  
     
   /** 等待工作线程把所有任务执行完毕*/  
   public void waitFinish() {  
       synchronized (this) {  
           isClosed = true;  
           notifyAll();            //唤醒所有还在getTask()方法中等待任务的工作线程  
       }  
       Thread[] threads = new Thread[activeCount()]; //activeCount() 返回该线程组中活动线程的估计值。  
       int count = enumerate(threads); //enumerate()方法继承自ThreadGroup类,根据活动线程的估计值获得线程组中当前所有活动的工作线程  
       for(int i =0; i < count; i++) { //等待所有工作线程结束  
           try {  
               threads[i].join();  //等待工作线程结束  
           }catch(InterruptedException ex) {  
               ex.printStackTrace();  
           }  
       }  
   }  
 
   /** 
   * 内部类,工作线程,负责从工作队列中取出任务,并执行 
    * @author sunnylocus 
    */  
   private class WorkThread extends Thread {  
      private int id;  
       public WorkThread(int id) {  
           //父类构造方法,将线程加入到当前ThreadPool线程组中  
           super(ThreadPoolUtil.this,id+"");  
           this.id =id;  
       }  
       public void run() {  
           while(! isInterrupted()) {  //isInterrupted()方法继承自Thread类,判断线程是否被中断  
               Runnable task = null;  
              try {  
                    task = getTask(id);     //取出任务  
              }catch(InterruptedException ex) {  
                  ex.printStackTrace();  
               }  
               //如果getTask()返回null或者线程执行getTask()时被中断,则结束此线程  
               if(task == null) return;  
                 
              try {  
                  task.run();  //运行任务  
               }catch(Throwable t) {  
                   t.printStackTrace();  
               }  
           }//  end while  
       }//  end run  
   }// end workThread 

//例子

public static void main(String[] args) throws Exception {


for (int i = 0; i < 1000; i++) {
ThreadPoolUtil.getInstance().execute(createTaskZipImg(i));
}

}
private static Runnable createTaskZipImg(final int i) {
return new Runnable() {
public void run() {
try {
System.out.println(i);
} catch (Exception e) {
}
}
};
}

}

///

ThreadPoolUtil.getInstance().execute(createTask(pointsSentObject));

private Runnable createTask(final RechargeLifeKfjPointsDTO points) {
return new Runnable() {
public void run() {
try {

callWltPointsRecharge(points);
} catch (Exception e) {
DevLog.error("muti thread exception", e);
}
}
};
}

private synchronized  void callWltPointsRecharge(final RechargeLifeKfjPointsDTO points){

try {
RechargeWltPointsResultDTO rechargeResult = rechargeWltPointsAmesbSAO.grantLifeKfjPoints(points);
String rechargeId = points.getRechargeId();
if(RechargeWltPointsResultDTO.ERROR_CODE_SUCCESSED.equalsIgnoreCase(rechargeResult.getErrorCode())){
//调用接口发放积分成功
wltPointsRechargeLogDAO.updateRechargeLogStatus(rechargeId,points.getPartyNo(), WltPointsRechargeLogDTO.RECHARGE_STATUS_SUCCESSED);
}else{
//调用接口发放积分失败
wltPointsRechargeLogDAO.updateRechargeLogStatus(rechargeId,points.getPartyNo(), WltPointsRechargeLogDTO.RECHARGE_STATUS_FAILED);
}
} catch (Exception e) {
DevLog.error("muti thread exception", e);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值