可以通过调用Executors类的静态newFixedThreadPool()方法来获取固定的线程池.
语法
ExecutorService fixedPool = Executors.newFixedThreadPool(2);
其中
最多2个线程将是处于活动状态以处理任务.
如果提交的线程超过2个,则它们将保留在队列中,直到线程可用.
如果线程在执行器执行关闭期间因故障而终止,则创建一个新线程取代它.
任何线程都存在,直到池关闭.
示例
以下TestThread程序在基于线程的环境中显示newFixedThreadPool方法的使用.
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(2); // Cast the object to its class type ThreadPoolExecutor pool = (ThreadPoolExecutor) executor; //Stats before tasks execution System.out.println("Largest executions: " + pool.getLargestPoolSize()); System.out.println("Maximum allowed threads: " + pool.getMaximumPoolSize()); System.out.println("Current threads in pool: " + pool.getPoolSize()); System.out.println("Currently executing threads: " + pool.getActiveCount()); System.out.println("Total number of threads(ever scheduled): " + pool.getTaskCount()); executor.submit(new Task()); executor.submit(new Task()); //Stats after tasks execution System.out.println("Core threads: " + pool.getCorePoolSize()); System.out.println("Largest executions: " + pool.getLargestPoolSize()); System.out.println("Maximum allowed threads: " + pool.getMaximumPoolSize()); System.out.println("Current threads in pool: " + pool.getPoolSize()); System.out.println("Currently executing threads: " + pool.getActiveCount()); System.out.println("Total number of threads(ever scheduled): " + pool.getTaskCount()); executor.shutdown(); } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println("Running Task! Thread Name: " + Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(duration); System.out.println("Task Completed! Thread Name: " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }}
这将产生以下结果.
输出
Largest executions: 0Maximum allowed threads: 2Current threads in pool: 0Currently executing threads: 0Total number of threads(ever scheduled): 0Core threads: 2Largest executions: 2Maximum allowed threads: 2Current threads in pool: 2Currently executing threads: 1Total number of threads(ever scheduled): 2Running Task! Thread Name: pool-1-thread-1Running Task! Thread Name: pool-1-thread-2Task Completed! Thread Name: pool-1-thread-2Task Completed! Thread Name: pool-1-thread-1
免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除