线程池加计数器使用

/**
 * f-road.com Inc.
 * Copyright (c) 2014 All Rights Reserved.
 */
package cn.com.froad.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <pre>
 *  积分池加计数器使用
 * </pre>
 *
 * @author xueyunlong
 * @create 2014年7月31日 下午3:26:30
 * @modify
 * @since   JDK1.6
 */
public class ExecutorCountDownTest {
    public static String alllist="";
     public static void main(String[] args) { 
            CountDownLatch runningThreadNum = new CountDownLatch(10);
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            // 创建10个任务并执行 
            for (int i = 0; i < 10; i++) { 
                executorService.execute(new MoreThread(runningThreadNum,String.valueOf(i))); 
            } 
            executorService.shutdown(); 
            try {
                runningThreadNum.await();
            } catch (InterruptedException e) {
                System.out.println(e);
            }
     
          System.out.println("alllist:"+alllist);
          alllist="";
        } 
    private static class MoreThread implements Runnable {
           
            private String value;//传入的数据列表
            private CountDownLatch runningThreadNum;

            public MoreThread(CountDownLatch runningThreadNum, String value) {
                this.runningThreadNum = runningThreadNum;
                this.value = value;
            }
            @Override
            public void run() {
                try {
                    Thread.sleep((long) (Math.random() * 10000)); 
                    //执行处理,调用接口
                    System.out.println("本次线程名称:"+Thread.currentThread().getName());
                    alllist +=value;
                    System.out.println(alllist);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    runningThreadNum.countDown();
                }
            }
        }
    } 
     

你可能感兴趣的:(线程池)