import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * @Description: * @author: fdy * @date: 2020/2/14 11:39 */ public class UserThreadFactory implements ThreadFactory { private final String namePrefix; private final AtomicInteger nextId = new AtomicInteger(1); public UserThreadFactory(String namePrefix) { // 设置线程的名称 this.namePrefix = "设置线程的名称: UserThreadFactory's "+ namePrefix+"-Worker-"; } @Override public Thread newThread(Runnable task) { String name = namePrefix + nextId.getAndIncrement(); Thread thread = new Thread(null, task, name, 0); System.out.println(thread.getName()); return thread; } } // 任务执行体 class Task implements Runnable{ private final AtomicLong count = new AtomicLong(0L); @Override * @Description:public void RUN () { System.out.println ( "running _" + count.getAndIncrement ()); } } / ** * @Description: Test Class * @author : FDY * @date: 2020/2/14 12 is: 10 * / public class UserRejectHandler the implements RejectedExecutionHandler { @Override public void rejectedExecution (the Runnable task, the ThreadPoolExecutor Executor) { System.out.println ( + "abnormality in the print task to the task information like reject rejected." executor.toString ()); } } / ** * @author : FDY @Date *: 2020/2/14 12:13 * / public class UserThreadPool { public static void main (String [] args) { // buffer queue of a fixed length of 2 is provided, in order to quickly trigger rejectHandler BlockingQueue Queue = new new a LinkedBlockingQueue (2 ); // assumed by external sources task thread mixing room room 1 and call 2 UserThreadFactory F1 = new new UserThreadFactory ( "first room" ); UserThreadFactory F2 = new new UserThreadFactory ( "second room" ); UserRejectHandler Handler = new new UserRejectHandler (); //The core thread is 1, maximum thread 2, in order to ensure trigger rejectHandler ThreadPoolExecutor threadPoolFirst = new new ThreadPoolExecutor (1,2,60 , TimeUnit.SECONDS, Queue, f1, Handler); // use the second instance to create a second thread factory thread pool ThreadPoolExecutor threadPoolSecond = new new ThreadPoolExecutor (1,2,60 , TimeUnit.SECONDS, Queue, F2, Handler); // create a task thread 400 task task = new new task (); for ( int i = 0; i <10 ; I ++ ) { threadPoolFirst.execute (Task); threadPoolSecond.execute (Task); } } }