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();
        }*/
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值