线程池(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());
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM