java线程池加队列 代码例子

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolQueue {
    public static BlockingQueue queue = new LinkedBlockingQueue();
    static final int nThreads = Runtime.getRuntime().availableProcessors() * 2;
    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, // corePoolSize线程池中核心线程数
            nThreads, // maximumPoolSize 线程池中最大线程数
            1, // 线程池中线程的最大空闲时间,超过这个时间空闲线程将被回收
            TimeUnit.DAYS, // 时间单位
            queue, // 队列
            new ThreadPoolExecutor.AbortPolicy());
    static {
        System.out.println("线程池---------------------------------------");
    }

    public static void main(String[] args) {

        for (int i = 0; i < 8; i++) {
            executor.execute(new Runnable() {
                public void run() {
                    long st=System.currentTimeMillis();
                    try {
                        Thread.sleep(1000 * 1);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    getCount();
                    System.out.println("执行任务"  );
                    System.out.println("线程名 " + Thread.currentThread().getName());
                    System.out.println("执行了 "+count+"任务 耗时:"+(System.currentTimeMillis()-st)+"毫秒");
                }
            });
        }


    }

    public volatile static int count = 0;

    public synchronized static int getCount() {
        ++count;
        return count;
    }
}

你可能感兴趣的:(java)