添加依赖,用于命名线程
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.2-jre</version> </dependency> //创建线程可执行方法 class PoolThread implements Runnable { int count = 1000; Object object = new Object(); @Override public void run() { while (true) { synchronized (object) { if (count <= 0) { break; } System.out.println("Thread.currentThread()= " + Thread.currentThread().getName() + "票数" + count--); if (count <= 0) { break; } } } } }
private void method2() throws InterruptedException { PoolThread poolThread = new PoolThread(); // ExecutorService executorService = Executors.newFixedThreadPool(5);容易造成内存溢出 ThreadFactory threadName = new ThreadFactoryBuilder().setNameFormat("myThread-pool-%d").build(); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 16, 3, TimeUnit.MINUTES, new LinkedBlockingQueue<>(20), threadName, new ThreadPoolExecutor.AbortPolicy()); threadPoolExecutor.execute(() -> System.out.println("Thread.currentThread() = " + Thread.currentThread().getName())); Thread.sleep(1000); threadPoolExecutor.execute(poolThread); threadPoolExecutor.execute(poolThread); //关闭线程池 threadPoolExecutor.shutdown(); threadPoolExecutor.awaitTermination(3, TimeUnit.SECONDS); System.out.println("执行完毕"); }