package com.zsElectric.boot.common.async;

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

/**
 * 自定义线程工厂
 * 用于设置线程优先级、守护线程状态等
 */
public class CustomThreadFactory implements ThreadFactory {
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
    private final ThreadGroup group;

    public CustomThreadFactory() {
        group = Thread.currentThread().getThreadGroup();
        namePrefix = "custom-async-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        
        // 设置线程为非守护线程
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        
        // 设置线程优先级
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        
        // 设置线程异常处理器
        t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            //当线程中发生未捕获的异常时，就会调用这个处理器。第二层：系统级异常处理
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.err.println("线程执行异常: " + t.getName() + ", 异常: " + e.getMessage());
            }
        });
        
        return t;
    }
}