package com.njzscloud.common.core.thread;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
    private final boolean virtual;

    public DefaultThreadFactory(boolean virtual, String poolName) {
        if (StrUtil.isBlank(poolName)) namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
        else namePrefix = poolName + "-";
        this.virtual = virtual;
    }

    @Override
    public Thread newThread(Runnable r) {
        String name = namePrefix + threadNumber.getAndIncrement();
        Runnable task = () -> {
            try {
                r.run();
            } finally {
                threadNumber.decrementAndGet();
            }
        };
        Thread.UncaughtExceptionHandler uncaughtExceptionHandler = (t1, e) -> log.error("线程异常：{}", t1.getName(), e);
        if (virtual) {
            return Thread.ofVirtual()
                .name(name)
                .uncaughtExceptionHandler(uncaughtExceptionHandler)
                .unstarted(task);
        } else {
            return Thread.ofPlatform()
                .name(name)
                .daemon(true)
                .uncaughtExceptionHandler(uncaughtExceptionHandler)
                .priority(Thread.NORM_PRIORITY)
                .unstarted(task);
        }

    }
}
