001/*
002 *  Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.agentsflex.core.util;
017
018import java.util.concurrent.ThreadFactory;
019import java.util.concurrent.atomic.AtomicInteger;
020
021/**
022 * @author michael yang (fuhai999@gmail.com)
023 */
024public class NamedThreadFactory implements ThreadFactory {
025
026    protected static final AtomicInteger POOL_COUNTER = new AtomicInteger(1);
027    protected final AtomicInteger mThreadCounter;
028    protected final String mPrefix;
029    protected final boolean mDaemon;
030    protected final ThreadGroup mGroup;
031
032    public NamedThreadFactory() {
033        this("pool-" + POOL_COUNTER.getAndIncrement(), false);
034    }
035
036    public NamedThreadFactory(String prefix) {
037        this(prefix, false);
038    }
039
040    public NamedThreadFactory(String prefix, boolean daemon) {
041        this.mThreadCounter = new AtomicInteger(1);
042        this.mPrefix = prefix + "-thread-";
043        this.mDaemon = daemon;
044        SecurityManager s = System.getSecurityManager();
045        this.mGroup = s == null ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
046    }
047
048    @Override
049    public Thread newThread(Runnable runnable) {
050        String name = this.mPrefix + this.mThreadCounter.getAndIncrement();
051        Thread ret = new Thread(this.mGroup, runnable, name, 0L);
052        ret.setDaemon(this.mDaemon);
053        return ret;
054    }
055
056    public ThreadGroup getThreadGroup() {
057        return this.mGroup;
058    }
059}