线程池(3)-参数-实现ThreadFactory

1.介绍

ThreadFactory用来创建线程,需要实现newThread方法。

2.常用场景

线程重命名

设置守护进程

设置优先级

3.示例(线程重命名)

public class ThreadFactoryCreateNewThread {

    static class MyThreadFactory implements ThreadFactory {
        private AtomicInteger atomicInteger = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            int index = atomicInteger.incrementAndGet();
            System.out.println("create no " + index + " thread");
            Thread t = new Thread(r, "Thread-" + index);
            return t;
        }
    }

    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.currentThread();
                    Thread.sleep(1000);
                    System.err.println(Thread.currentThread().getName());
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newFixedThreadPool(5, new MyThreadFactory());
        es.execute(new MyRunnable());
        es.execute(new MyRunnable());
    }
}
原文地址:https://www.cnblogs.com/SmilingEye/p/11752741.html