线程池学习(五)线程工厂、线程池工厂

  • Executors 定义的Executor, ExecutorService, ScheduledExecutorService,
    ThreadFactory和Callable类的工厂和实用程序方法,我们称为线程池工厂。
  • ThreadFactory 为定制化创建新线程的对象,我们称为线程工厂

前面几期的学习中,我已经初步会使用线程池了,也已经使用了 Executors
这里介绍下 ThreadFactory 的使用

public interface ThreadFactory {

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     *         create a thread is rejected
     */
    Thread newThread(Runnable r);
}

使用举例:

@Slf4j
public class ExecutorsTest {

    static class TargetTask implements Runnable {
        public static final int SLEEP_GAP = 1000;
        // AtomicInteger 提供了一种线程安全的方式来对整数进行操作。它可以保证多个线程同时对同一个AtomicInteger对象进行操作时,不会出现数据竞争和不一致的情况
        static AtomicInteger taskNo = new AtomicInteger(0);
        String taskName;

        @Override
        public void run() {
            log.info(Thread.currentThread().getName()+": "+taskName + "is running ...");
            try {
                Thread.sleep(SLEEP_GAP);
            } catch (Exception e) {
                log.error(Thread.currentThread().getName()+": "+taskName + "running error !");
                e.printStackTrace();
            }
            log.info(Thread.currentThread().getName()+": "+ taskName + "is  end ...");

        }

        TargetTask() {
            taskName = "task_" + taskNo;
            taskNo.incrementAndGet();
        }
    }

    static class TargetTaskWithError extends TargetTask {
        public void run() {
            super.run();//执行父类的run方法
            // 强行抛出异常
            throw new RuntimeException("Error from " + taskName);
        }
    }

    static class MyThreadFactory implements ThreadFactory {
        static AtomicInteger threadNo = new AtomicInteger(1);

        @Override
        public Thread newThread(@NotNull Runnable r) {
            String threadName = "MyThreadFactory_" + threadNo;
            log.info("使用线程工厂创建一个线程 名字:" + threadName);
            threadNo.incrementAndGet();
            return new Thread(r, threadName);
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
    //        // 使用默认的 线程工厂
//        ExecutorService poll8 = Executors.newFixedThreadPool(2);
//        poll8.execute(new TargetTask());
//        poll8.shutdown();

        // 使用自定义的 线程工厂
        ExecutorService poll9 = Executors.newFixedThreadPool(2, new MyThreadFactory());
        poll9.execute(new TargetTask());
        poll9.shutdown();
    }
}

使用自定义的 线程工厂 结果中会打印出自定义的线程名 MyThreadFactory_
线程池学习(五)线程工厂、线程池工厂_第1张图片
使用默认的 线程工厂 结果中会打印出默认的线程名pool_

线程池学习(五)线程工厂、线程池工厂_第2张图片

你可能感兴趣的:(#,线程,java,开发语言,多线程,线程池)