ThreadFactory 实例创建方式

匿名内部类

private final Executor executor;

{
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    };
    executor = Executors.newFixedThreadPool(shops.size(), threadFactory);
}
private final Executor executor = Executors.newFixedThreadPool(shops.size(), new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
    }
});

lambda 表达式

private final Executor executor = Executors.newFixedThreadPool(shops.size(), r -> {
    Thread t = new Thread(r);
    t.setDaemon(true);
    return t;
});

ThreadFactoryBuilder

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.concurrent.ThreadFactory;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ExecuterThreadFactoryBuilder {
    public static ThreadFactory build() {
        return new ThreadFactoryBuilder().setDaemon(true).setNameFormat("thread-%d").build();
    }

    public static ThreadFactory build(String nameFormat) {
        return new ThreadFactoryBuilder().setDaemon(true).setNameFormat(nameFormat).build();
    }
}

private final Executor executor = Executors.newFixedThreadPool(shops.size(), ExecuterThreadFactoryBuilder.build());

你可能感兴趣的:(并发编程,最佳实践,java)