java 有四种线程池
1、可缓存线程池
newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收
2、定长线程池 可控制最大并发数
newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
package com.zyh.controller.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 学习并发编程 * * @author 1101399 * @CreateDate 2018-7-31 下午2:28:29 */ public class ThreadTestTwo { public static void main(String[] args) { // 可缓存线程池 ExecutorService excutorOne = Executors.newCachedThreadPool(); // 定长线程池 可控制最大并发数 ExecutorService excutorTwo = Executors.newFixedThreadPool(2); StringBuffer nameOne = new StringBuffer("A"); excutorOne.submit(new ThreadOne(nameOne)); StringBuffer nameTwo = new StringBuffer("B"); excutorOne.submit(new ThreadOne(nameTwo)); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } StringBuffer nameThree = new StringBuffer("C"); excutorOne.submit(new ThreadOne(nameThree)); System.out.println(" ******************************************* "); excutorTwo.submit(new ThreadOne(nameOne)); excutorTwo.execute(new ThreadOne(nameTwo)); excutorTwo.submit(new ThreadOne(nameThree)); System.out.println(" ******************************************* "); } public static class ThreadOne implements Runnable { public StringBuffer name; public ThreadOne(StringBuffer name) { this.name = name; } @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("ThreadOne name:" + name + " ID:" + Thread.currentThread().getId()); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
3、单线程化线程池
newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
package com.zyh.controller.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * student threads * * @author 1101399 * @CreateDate 2018-7-30 下午2:09:01 */ public class ThreadTestOne { public static void main(String[] args) throws InterruptedException { final ThreadTest A1 = new ThreadTest("A1"); final ThreadTest A2 = new ThreadTest("A2"); final ThreadTest A3 = new ThreadTest("A3"); A1.start(); A2.start(); A1.join(); A2.join(); System.out.println("方法一实现多线程"); if (!A1.isAlive()) {// A1 线程不存在的时候控制台打印一条信息 System.out.println("A1执行完毕?!"); } final Thread B1 = new Thread(new RunnableTest("B1")); B1.start(); final Thread B2 = new Thread(new RunnableTest("B2")); B2.start(); B1.join(); B2.join(); System.out.println("方法二实现多线程"); /** * 直接实现线程的开辟 FIXME */ final Thread C1 = new Thread(new Runnable() { @Override public void run() { try { A1.join(); A2.join(); B1.join(); B2.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < 2; i++) { System.out.println("··············"); } } }); C1.start(); C1.join(); System.out.println("方法三实现多线程"); System.out.println("线程池的应用"); // 线程池的学习&应用 // 单线程化线程池 ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(A1); executor.submit(A2); executor.submit(A3); executor.execute(B1);// 这种样子的线程类就是不执行 executor.execute(A1); executor.submit(B1);// 这三种线程的实现方式之前不能 XXX start()启动线程 executor.submit(B2);// 这三种线程的实现方式之前不能 XXX start()启动线程 executor.submit(C1);// 这三种线程的实现方式之前不能 XXX start()启动线程 executor.shutdown();// 停止传入任务 // executor.shutdownNow();// 停止线程池-对线程池说STOP // 会导致线程池中第一个线程的sleep出现sleep interrupted异常 // 该函数的核心是:它向该线程发起interrupt()请求,而sleep()方法遇到有interrupt()请求时,会抛出InterruptedException(),并继续往下执行 // 运行到这条语句直接停止线程池-检测线程停止后执行的join()函数毫无意义,不能生效 } /** * 继承Thread来实现多线程编程 FIXME */ public static class ThreadTest extends Thread { public String nameOne; public StringBuffer nameTwo; public StringBuilder nameThree; private long time; // 构造函数 public ThreadTest(String name) { this.nameOne = name; } // 构造函数 public ThreadTest(String name, long time) { this.nameOne = name; this.time = time; } @Override public void run() { for (int i = 0; i < 2; i++) { System.out.println(this.nameOne + " Thread运行第 " + i + " 次!"); try { if (this.time != 0) { sleep(this.time + i); System.out.println(this.nameOne + "-time-" + (time + i)); } else { // sleep((int) Math.random() * 1000); sleep(50); System.out .println(this.nameOne + "-random-" + (int) (Math.random() * 1000)); } } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * 实现接口Runnable来实现多线程编程 FIXME */ public static class RunnableTest implements Runnable { public String nameOne; public StringBuffer nameTwo; public StringBuilder nameThree; private long time; public RunnableTest(String name) { this.nameOne = name; } public RunnableTest(String name, long time) { this.nameOne = name; this.time = time; } @Override public void run() { for (int i = 0; i < 2; i++) { System.out.println(this.nameOne + " Runnable运行第 " + i + " 次!"); try { if (this.time != 0) { Thread.sleep(this.time + i); System.out.println(this.nameOne + "-time-" + (time + i)); } else { Thread.sleep((int) Math.random() * 1000); System.out .println(this.nameOne + "-random-" + (int) (Math.random() * 1000)); } } catch (InterruptedException e) { e.printStackTrace(); } } } } }
4、定长 定时周期性线程池
newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行
package com.zyh.controller.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * 学习java并发编程之定时线程池 & 探讨单例模式 * * @author 1101399 * @CreateDate 2018-8-1 上午9:42:20 */ public class ThreadTestThree { public static void main(String[] args){ System.out.println("**********************************"); // 定长定时线程池 /* ExecutorService 普通执行类 */ ExecutorService excutor = Executors.newScheduledThreadPool(2); StringBuffer nameOne = new StringBuffer("this is Thread A"); excutor.submit(new ThreadOne(nameOne)); try { excutor.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } StringBuffer nameTwo = new StringBuffer("this is Thread B"); excutor.submit(new ThreadOne(nameTwo)); try { excutor.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } StringBuffer nameThree = new StringBuffer("this is Thread C"); excutor.submit(new ThreadOne(nameThree)); try { excutor.awaitTermination(0, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("**********************************"); // 定长定时线程池 TODO 关键的 FIXME /* ScheduledExecutorService 定期执行类 */ ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(2); StringBuffer nameFour = new StringBuffer("Scheduled test to A"); scheduledExecutor.schedule(new ThreadOne(nameFour), 10, TimeUnit.SECONDS); StringBuffer nameFive = new StringBuffer("Scheduled test to B"); scheduledExecutor.schedule(new ThreadOne(nameFive), 5, TimeUnit.SECONDS); StringBuffer nameSix = new StringBuffer("Scheduled test to C | 定期操作 | 以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕,如果上一个任务执行完毕,则当前任务立即执行,如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行"); scheduledExecutor.scheduleAtFixedRate(new ThreadOne(nameSix), 5, 10,TimeUnit.SECONDS); StringBuffer nameSeven = new StringBuffer("Scheduled test to D | 定期操作 | 以上一个任务结束时开始计时,period时间过去后,立即执行"); scheduledExecutor.scheduleWithFixedDelay(new ThreadOne(nameSeven), 5, 10,TimeUnit.SECONDS); System.out.println("**********************************"); System.out.println("**********************************"); } /** * 通过实现接口实现线程开发 * * @author 1101399 * @CreateDate 2018-8-1 上午9:45:16 */ private static class ThreadOne implements Runnable{ public StringBuffer name; public ThreadOne(StringBuffer name){ this.name = name; } @Override public void run(){ for(int i = 0; i < 5; i++){ System.out.println("Thread name:" + name + " | Thread Id " + Thread.currentThread().getId()); try{ Thread.sleep(500); }catch(InterruptedException e){ e.printStackTrace(); } } } } /* 单例模式的创建还需学习 挂起 public class SingleCaseOne{// 懒汉模式 private static SingleCaseOne singleCase = null; private SingleCaseOne(){}// 私有构造函数用以保证其他对象不能直接new一个该对象的实例出来 public static SingleCaseOne getClass(){ return singleCase; } } public class SingleCaseTwo{ private static SingleCaseTwo singleCase = new SingleCaseTwo(); private SingleCaseTwo(){}// 私有构造函数用以保证其他对象不能直接new一个该对象的实例出来 public static SingleCaseTwo getClass(){ return singleCase; } } */ }