001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (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 io.jboot.utils; 017 018import java.util.concurrent.ThreadFactory; 019import java.util.concurrent.atomic.AtomicInteger; 020 021/** 022 * @author michael yang (fuhai999@gmail.com) 023 * @Date: 2019/11/21 024 */ 025public class NamedThreadFactory implements ThreadFactory { 026 027 protected static final AtomicInteger POOL_COUNTER = new AtomicInteger(1); 028 protected final AtomicInteger mThreadCounter; 029 protected final String mPrefix; 030 protected final boolean mDaemon; 031 protected final ThreadGroup mGroup; 032 033 public NamedThreadFactory() { 034 this("pool-" + POOL_COUNTER.getAndIncrement(), false); 035 } 036 037 public NamedThreadFactory(String prefix) { 038 this(prefix, false); 039 } 040 041 public NamedThreadFactory(String prefix, boolean daemon) { 042 this.mThreadCounter = new AtomicInteger(1); 043 this.mPrefix = prefix + "-thread-"; 044 this.mDaemon = daemon; 045 SecurityManager s = System.getSecurityManager(); 046 this.mGroup = s == null ? Thread.currentThread().getThreadGroup() : s.getThreadGroup(); 047 } 048 049 @Override 050 public Thread newThread(Runnable runnable) { 051 String name = this.mPrefix + this.mThreadCounter.getAndIncrement(); 052 Thread ret = new Thread(this.mGroup, runnable, name, 0L); 053 ret.setDaemon(this.mDaemon); 054 return ret; 055 } 056 057 public ThreadGroup getThreadGroup() { 058 return this.mGroup; 059 } 060}