firstGroup-pool-1-thread-1
firstGroup-pool-1-thread-2
secondGroup-pool-2-thread-1
secondGroup-pool-2-thread-2
secondGroup-pool-2-thread-3package com.javarush.task.task28.task2802;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/*
Пишем свою ThreadFactory
*/
public class Solution {
public static void main(String[] args) {
class EmulatorThreadFactoryTask implements Runnable {
@Override
public void run() {
emulateThreadFactory();
}
}
ThreadGroup group = new ThreadGroup("firstGroup");
Thread thread = new Thread(group, new EmulatorThreadFactoryTask());
ThreadGroup group2 = new ThreadGroup("secondGroup");
Thread thread2 = new Thread(group2, new EmulatorThreadFactoryTask());
thread.start();
thread2.start();
}
private static void emulateThreadFactory() {
AmigoThreadFactory factory = new AmigoThreadFactory();
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
factory.newThread(r).start();
factory.newThread(r).start();
factory.newThread(r).start();
}
public static class AmigoThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final int namePrefix;
private final AtomicInteger treadNumber = new AtomicInteger();
private final ThreadGroup group;
private AmigoThreadFactory() {
namePrefix = poolNumber.getAndIncrement();
group = Thread.currentThread().getThreadGroup();
}
@Override
public Thread newThread(Runnable r) {
Thread tr = new Thread(group, r);
tr.setName(tr.getThreadGroup().getName() + "-pool-" +
namePrefix +
"-thread-" +
treadNumber.incrementAndGet());
if (tr.isDaemon())
tr.setDaemon(false);
if (tr.getPriority() != Thread.NORM_PRIORITY)
tr.setPriority(Thread.NORM_PRIORITY);
return tr;
}
}
}