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

 

相关文章:

  • 2022-01-17
  • 2021-12-19
  • 2021-06-28
  • 2022-12-23
  • 2021-08-05
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-15
  • 2022-01-08
  • 2021-12-22
  • 2022-12-23
  • 2022-02-08
  • 2021-11-13
相关资源
相似解决方案