- package com.thread.app01;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class App01 implements Runnable {
- int count = 100;
- @Override
- public void run() {
- this.Ticketing();
- }
- public void Ticketing() {
- while (count != 0) {
- System.out.println(Thread.currentThread().getName() + " " + "当前"
- + count--);
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- App01 app01 = new App01();
- /**
- * <b>Executors.newCachedThreadPool()</b>
- * <p>
- * 创建一个可根据需要创建新线程的线程池,但是在以前构 造的线程可用时将重用它们,并在需要的时使用提供的TherdFacory创建线程
- * </p>
- * <p>
- * 在程序执行过程中通常会创建与所需数量相同的线程,然后在它回收旧线程时停止创建新线程
- * </p>
- */
- ExecutorService exec = Executors.newCachedThreadPool();
- for (int i = 0; i < 4; i++) {
- exec.execute(app01);
- }
- exec.shutdown();
- /**
- * <b>Executors.newFixedThreadPool(int count);</b>
- * <p>
- * 创建一个可重用固定线程的线程池,以共享的×××队列方式运行这些线程
- * </p>
- * <p>
- * 预先执行代价高昂的线程分配,因而也就可以跟制线程的数量
- * <p>
- */
- ExecutorService exec1 = Executors.newFixedThreadPool(5);
- for (int i = 0; i < 4; i++) {
- exec1.execute(app01);
- }
- exec1.shutdown();
- /**
- * <b>Executors.newSingleThreadExecutor()</b>
- * <p>
- * 创建一个单用单个worker线程的Executor,以×××队列方式运行
- * <p>
- * <p>
- * 这种方式更好的解决资源上同步,省去只是为了维持某些事物的原型而进行各种协调
- * <P>
- */
- ExecutorService exec2 = Executors.newSingleThreadExecutor();
- for (int i = 0; i < 4; i++) {
- exec2.execute(app01);
- }
- exec2.shutdown();
- }
- }