線程池(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