package com.dy.pool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * ExecutorService 真正的线程池接口。 ScheduledExecutorService 能和Timer/TimerTask相似,解决那些须要任务重复执行的问题。 ThreadPoolExecutor是ExecutorService的默认实现。 ScheduledThreadPoolExecutor继承ThreadPoolExecutor的ScheduledExecutorService接口实现,周期性任务调度的类实现。 * 在Executors类里面提供了一些静态工厂,生成一些经常使用的线程池。 * 2.newFixedThreadPool 建立固定大小的线程池。每次提交一个任务就建立一个线程,直到线程达到线程池的最大大小。 线程池的大小一旦达到最大值就会保持不变,若是某个线程由于执行异常而结束,那么线程池会补充一个新线程 */ public class FixedThreadPool { public static void main(String[] args) { System.out.println("欢迎来到线程世界!"); //建立一个可重用固定线程数的线程池 ExecutorService pool = Executors.newFixedThreadPool(2); //建立实现了Runnable接口对象,Thread对象固然也实现了Runnable接口 FixedThreadPool.MyThread t1 = new FixedThreadPool().new MyThread(); FixedThreadPool.MyThread t2 = new FixedThreadPool().new MyThread(); FixedThreadPool.MyThread t3 = new FixedThreadPool().new MyThread(); FixedThreadPool.MyThread t4 = new FixedThreadPool().new MyThread(); //将线程放入池中进行执行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); //关闭线程池 pool.shutdown(); } class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在执行。。。"); } } }
另外说下 代码中的this.getName和Thread.currentThread().getName(): java
前者的this是指实例对象自身,后者是指实例对象中的当前执行线程;两者不要理解混淆了! ide
类模型: this