java线程池(三)之newSingleThreadExecutor

newSingleThreadExecutor测试类

package com.thread.pool;

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

public class TestSingleThreadExecutor {
    public static void main(String[] args) {
        /**
         * FinalizableDelegatedExecutorService
         *             (new ThreadPoolExecutor(1, 1,
         *                                     0L, TimeUnit.MILLISECONDS,
         *                                     new LinkedBlockingQueue<Runnable>()));
         *
         *  核心线程数为1,最大线程数为1,超出核心线程数的线程(一般来说不会出现超出核心数的线程,具体为啥,请看线程执行任务步骤)的存活时间为0,
         *  无边界的队列,会将来到的任务都放到队列中
         *
         *  此种线程池中只有一个线程,这样会保证顺序的执行各个按照时间到达的任务。
         */
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i=0; i<10; i++){
            Thread thread = new Thread(new ThreadPool("" + i));

            executorService.execute(thread);//会看到是按顺序执行的,name=1到name=9
        }

        executorService.shutdown();
    }
}



线程任务测试类

package com.thread.pool;

import java.util.Date;

public class ThreadPool implements Runnable {

    private static ThreadPool threadPool = null;
    String name;

    public ThreadPool(String name){
        this.name = name;
    }
    @Override
    public void run() {
        doSomeThing();
    }

    public static synchronized Runnable getInstance(){
        if(threadPool == null){
            threadPool = new ThreadPool("getInstance");
        }
        return getInstance();
    }

    private void doSomeThing() {

        for (int i=0;i<10;i++){
            System.out.println((new Date()).toLocaleString() + "   " + Thread.currentThread().getName() + "执行" +i + ",name=" + name);
        }

       /* try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }
}

上一篇:关于StackExchange.Redis的超时问题


下一篇:C++实现简易线程池