烟台网站制作专业上海全网推广
publicclassMyThreadextends Thread { @Override publicvoid run() { System.out.println(Thread.currentThread().getName() + "正在执行。。。"); }
}
publicclassTestSingleThreadExecutor { publicstaticvoid main(String[] args) { //创建一个可重用固定线程数的线程池 ExecutorService pool = Executors. newSingleThreadExecutor(); //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口 Thread t1 =new MyThread(); Thread t2 =new MyThread(); Thread t3 =new MyThread(); Thread t4 =new MyThread(); Thread t5 =new MyThread(); //将线程放入池中进行执行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //关闭线程池 pool.shutdown(); }
}
publicclass TestFixedThreadPool { publicstaticvoid main(String[] args) { //创建一个可重用固定线程数的线程池 ExecutorService pool = Executors.newFixedThreadPool(2); //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口 Thread t1 =new MyThread(); Thread t2 =new MyThread(); Thread t3 =new MyThread(); Thread t4 =new MyThread(); Thread t5 =new MyThread(); //将线程放入池中进行执行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //关闭线程池 pool.shutdown(); }
}
publicclass TestCachedThreadPool { publicstaticvoid main(String[] args) { //创建一个可重用固定线程数的线程池 ExecutorService pool = Executors.newCachedThreadPool(); //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口 Thread t1 =new MyThread(); Thread t2 =new MyThread(); Thread t3 =new MyThread(); Thread t4 =new MyThread(); Thread t5 =new MyThread(); //将线程放入池中进行执行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //关闭线程池 pool.shutdown(); }
}
pool-1-thread-1正在执行。。。pool-1-thread-1正在执行。。。pool-1-thread-1正在执行。。。pool-1-thread-1正在执行。。。pool-1-thread-1正在执行。。。
publicclass TestScheduledThreadPoolExecutor { publicstaticvoid main(String[] args) { ScheduledThreadPoolExecutor exec =new ScheduledThreadPoolExecutor(1); exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间就触发异常 @Override publicvoid run() { //throw new RuntimeException(); System.out.println("================"); } }, 1000, 5000, TimeUnit.MILLISECONDS); exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的 @Override publicvoid run() { System.out.println(System.nanoTime()); } }, 1000, 2000, TimeUnit.MILLISECONDS);}
}
ThreadPoolExecutor详解ThreadPoolExecutor的完整构造方法的签名是:
ThreadPoolExecutor(
int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit
, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory
, RejectedExecutionHandler handler
) .corePoolSize - 池中所保存的线程数,包括空闲线程。
maximumPoolSize-池中允许的最大线程数。
keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。
unit - keepAliveTime 参数的时间单位。
workQueue - 执行前用于保持任务的队列。
此队列仅保持由 execute方法提交的 Runnable任务。
threadFactory - 执行程序创建新线程时使用的工厂。
handler - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。ThreadPoolExecutor是Executors类的底层实现。
在JDK帮助文档中,有如此一段话:“强烈建议程序员使用较为方便的Executors工厂方法Executors.newCachedThreadPool()(无界线程池,可以进行自动线程回收)、Executors.newFixedThreadPool(int)(固定大小线程池)Executors.newSingleThreadExecutor()(单个后台线程)它们均为大多数使用场景预定义了设置。”下面介绍一下几个类的源码:ExecutorService newFixedThreadPool (int nThreads):固定大小线程池。
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}
public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));}
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}
new ThreadPoolExecutor(2, 3, 30, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),new RecorderThreadFactory("CookieRecorderPool"),new ThreadPoolExecutor.CallerRunsPolicy()
);
new ThreadPoolExecutor(2, 3, 30, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),new RecorderThreadFactory("CookieRecorderPool"),new ThreadPoolExecutor.CallerRunsPolicy()
); 当核心线程已经有2个正在运行.
new ThreadPoolExecutor(2, 4, 30, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(2),new RecorderThreadFactory("CookieRecorderPool"),new ThreadPoolExecutor.CallerRunsPolicy());new ThreadPoolExecutor( 2, 4, 30, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(2),new RecorderThreadFactory("CookieRecorderPool"),new ThreadPoolExecutor.CallerRunsPolicy());
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { r.run(); }
}
这个策略显然不想放弃执行任务。但是由于池中已经没有任何资源了,那么就直接使用调用该execute的线程本身来执行。AbortPolicy:处理程序遭到拒绝将抛出运行时RejectedExecutionException
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {throw new RejectedExecutionException();}
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {}
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {if (!e.isShutdown()) {e.getQueue().poll();e.execute(r);}
}
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}