interface ThreadFactory

本文详细介绍了Java并发包中ThreadFactory接口的作用与实现,解释了如何使用ThreadFactory创建线程,以及它如何帮助应用程序使用特殊的线程子类、优先级等特性。通过示例代码展示了ThreadFactory的简单实现,并提到了Executors提供的更实用的默认实现。
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;

/**
 * An object that creates new threads on demand.  Using thread factories
 * removes hardwiring of calls to {@link Thread#Thread(Runnable) new Thread},
 * enabling applications to use special thread subclasses, priorities, etc.
 *
 * <p>
 * The simplest implementation of this interface is just:
 *  <pre> {@code
 * class SimpleThreadFactory implements ThreadFactory {
 *   public Thread newThread(Runnable r) {
 *     return new Thread(r);
 *   }
 * }}</pre>
 *
 * The {@link Executors#defaultThreadFactory} method provides a more
 * useful simple implementation, that sets the created thread context
 * to known values before returning it.
 * @since 1.5
 * @author Doug Lea
 */
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);
}

ThreadFactory.java

好的,接下来下一个模块,eventcenter-core:@Getter @Setter @ConfigurationProperties(prefix = “event-center.common”) public class CommonProperties { /** * 尝试获取锁的超时时间,单位second */ private long lockTimeout = 10; /** * 线程池的名字 */ private String threadName = "event_center"; /** * 消费者ID前缀(服务的名字) */ private String consumerIdPrefix = "consumer"; /** * topic的前缀,默认为null */ private String topicPrefix; /** * 忽略Prefix的topic列表,默认为null */ private List<String> ignorePrefixTopic; }@Slf4j public class IdGenerator { private final String consumerIdPrefix; public IdGenerator(String prefix, @Nullable String hostName) { if (Objects.isNull(hostName)) { consumerIdPrefix = prefix + "_" + "UNKNOWN_HOSTNAME"; } else { consumerIdPrefix = prefix + "_" + hostName; } } /** * 产生分布式系统下唯一的消费者Id * * @return 产生的consumerId */ public String createConsumerId() { return consumerIdPrefix + "_" + UUID.randomUUID().toString(); } /** * 产生分布式系统下唯一的消费者组Id * * @param topic 消费者组对应的topic * @return 产生的groupId */ public String createGroupId(String topic) { return topic + "_" + UUID.randomUUID().toString(); } }@Slf4j @SuppressWarnings(“unused”) public final class ThreadFactoryBuilder { private String nameFormat = null; private Boolean daemon = null; private Integer priority = null; private UncaughtExceptionHandler uncaughtExceptionHandler = null; private ThreadFactory backingThreadFactory = null; /** * Creates a new {@link ThreadFactory} builder. */ public ThreadFactoryBuilder() { // empty } /** * Sets the naming format to use when naming threads ({@link Thread#setName}) which are created with this * ThreadFactory. * * @param nameFormat a {@link String#format(String, Object...)}-compatible format String, to which a unique integer * (0, 1, etc.) will be supplied as the single parameter. This integer will be unique to the built * instance of the ThreadFactory and will be assigned sequentially. For example, {@code * "rpc-pool-%d"} will generate thread names like {@code "rpc-pool-0"}, {@code "rpc-pool-1"}, * {@code "rpc-pool-2"}, etc. * @return this for the builder pattern */ public ThreadFactoryBuilder setNameFormat(String nameFormat) { // fail fast if the format is bad or null String unused = format(nameFormat, 0); log.trace("ThreadFactoryBuilder nameFormat example: {}", unused); this.nameFormat = nameFormat; return this; } /** * Sets daemon or not for new threads created with this ThreadFactory. * * @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads * @return this for the builder pattern */ public ThreadFactoryBuilder setDaemon(boolean daemon) { this.daemon = daemon; return this; } /** * Sets the priority for new threads created with this ThreadFactory. * * @param priority the priority for new Threads created with this ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setPriority(int priority) { // Thread#setPriority() already checks for validity. These error messages // are nicer though and will fail-fast. checkArgument( priority >= Thread.MIN_PRIORITY, "Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY); checkArgument( priority <= Thread.MAX_PRIORITY, "Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY); this.priority = priority; return this; } /** * Sets the {@link UncaughtExceptionHandler} for new threads created with this ThreadFactory. * * @param uncaughtExceptionHandler the uncaught exception handler for new Threads created with this ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setUncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler) { this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler); return this; } /** * Sets the backing {@link ThreadFactory} for new threads created with this ThreadFactory. Threads will be created * by invoking #newThread(Runnable) on this backing {@link ThreadFactory}. * * @param backingThreadFactory the backing {@link ThreadFactory} which will be delegated to during thread creation. * @return this for the builder pattern */ public ThreadFactoryBuilder setThreadFactory(ThreadFactory backingThreadFactory) { this.backingThreadFactory = checkNotNull(backingThreadFactory); return this; } /** * Returns a new thread factory using the options supplied during the building process. After building, it is still * possible to change the options used to build the ThreadFactory and/or build again. State is not shared amongst * built instances. * * @return the fully constructed {@link ThreadFactory} */ public ThreadFactory build() { return doBuild(this); } // Split out so that the anonymous ThreadFactory can't contain a reference back to the builder. // At least, I assume that's why. private static ThreadFactory doBuild(ThreadFactoryBuilder builder) { final String nameFormat = builder.nameFormat; final Boolean daemon = builder.daemon; final Integer priority = builder.priority; final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler; final ThreadFactory backingThreadFactory = Objects.nonNull(builder.backingThreadFactory) ? builder.backingThreadFactory : Executors.defaultThreadFactory(); final AtomicLong count = Objects.nonNull(nameFormat) ? new AtomicLong(0) : null; return runnable -> { Thread thread = backingThreadFactory.newThread(runnable); if (Objects.nonNull(nameFormat)) { thread.setName(format(nameFormat, count.getAndIncrement())); } if (Objects.nonNull(daemon)) { thread.setDaemon(daemon); } if (Objects.nonNull(priority)) { thread.setPriority(priority); } if (Objects.nonNull(uncaughtExceptionHandler)) { thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); } return thread; }; } private static String format(String format, Object... args) { return String.format(Locale.ROOT, format, args); } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @since 20.0 (varargs overload since 2.0) */ private static void checkArgument(boolean b, @Nullable String errorMessageTemplate, int p1, int p2) { if (!b) { throw new IllegalArgumentException(String.valueOf(errorMessageTemplate) + p1 + p2); } } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ private static <T> T checkNotNull(T reference) { if (Objects.isNull(reference)) { throw new NullPointerException(); } return reference; } }public interface ConsumerTask { /** * 获取Task对应的handler * * @return EventHandler */ Handler getHandler(); /** * 获取Task对应的业务线程池 * * @return ExecutorService */ ExecutorService getExecutorService(); /** * task是否运行 * * @return task是否运行 */ default boolean isRunning() { return true; } } @Slf4j public class DataProcessor implements Runnable { private final Event event; private final EventHandler handler; public DataProcessor(Event event, EventHandler handler) { this.event = event; this.handler = handler; } @Override public void run() { try { handler.handleEvent(event); } catch (Exception e) { log.error("Fail to process event, handler:{}", handler.getClass().getName(), e); } } } @Slf4j public class GenericDataProcessor implements Runnable { private final T event; private final GenericEventHandler<T> handler; public GenericDataProcessor(T event, GenericEventHandler<T> handler) { this.event = event; this.handler = handler; } @Override public void run() { try { handler.handleEvent(event); } catch (Exception e) { log.error("Fail to process event, handler:{}", handler.getClass().getSimpleName(), e); } } }
09-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值