Thread Pool (3) - Parameters - achieve ThreadFactory

1 Introduction

ThreadFactory used to create a thread, the need to achieve newThread method.

2. Common scene

Rename thread

Daemon

Setting priorities

Example 3. (threads rename)

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() {
            while (true) {
                try {
                    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());
    }
}

 

Guess you like

Origin www.cnblogs.com/SmilingEye/p/11752741.html