美文网首页
项目中ThreadGroup的使用

项目中ThreadGroup的使用

作者: 陈萍儿Candy | 来源:发表于2020-10-30 08:31 被阅读0次
/**
     * 线程工厂类,用来生产线程池需要的线程
     * 1、{@link ChenTask#PRIORITY_TOP}及以上优先级的任务,会创建高优先级线程;
     * 2、{@link ChenTask#PRIORITY_LOW}及以下优先级的任务,会创建低优先级线程
     * 3、其他优先级任务,会创建普通优先级线程;
     */
    private static class ChenThreadFactory implements ThreadFactory {

        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        ChenThreadFactory() {
            this("chen-common-thread");
        }

        ChenThreadFactory(String namePrefix) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            this.namePrefix = namePrefix + "-pool-%1$d-thread-%2$d";
        }

        @Override
        public Thread newThread(Runnable r) {
        //  创建线程
            Thread t = new Thread(group, r, String.format(namePrefix, poolNumber.getAndIncrement(), threadNumber.getAndIncrement()), 0);
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }

问题:创建线程时为什么不用下面这个构造??????
传入group有什么好处吗????

public Thread(Runnable target, String name) {
        init(null, target, name, 0);
    }

相关文章

网友评论

      本文标题:项目中ThreadGroup的使用

      本文链接:https://www.haomeiwen.com/subject/nnffvktx.html