【高性程】Java原理(JVM 、JDK)

1.1.1Java运行原理

1.class文件内容

class文件包含Java程序执行的字节码;数据严格按照格式紧凑排列在class文件中的二进制流,中间无任何分隔符;文件开头有一个0xcafebabe(16进制)特殊的一个标志。
在这里插入图片描述

2.jvm运行时数据区【jvm规范】

在这里插入图片描述
线程独占:每个线程都会有它独立的空间,随着线程生命周期而创建和销毁。
线程共享:所有线程能访问这块内存数据,随着虚拟机或者GC而创建和销毁。

(1)方法区

jvm用来存储加载的类信息、常量、静态变量、编译后的代码等数据。
虚拟机规范中这是一个逻辑区域。具体实现根据不同虚拟机来实现。
如:Oracle的Hotspot在Java7中方法区放在永久代,Java8放在元素数据空间,并且通过GC机制对这个区域进行管理。

(2)堆内存

堆内存可以细分为:老年代、新生代(Eden 、From Survivor 、To Survivor)
JVM启动时创建,存放对象的实例。垃圾回收器主要就是管理堆内存。
如果满了,就会出现OutOfMemoryError。

(3)虚拟机栈

虚拟机栈是为了虚拟机执行Java方法而准备的。
每个线程都在这个空间有一个私有的空间。
线程栈由多个栈帧(Stack Frame)组成。
一个线程会执行一个方法或多个方法,一个方法对应一个栈帧。
栈帧内容包含:局部变量表、操作数栈、动态链接、方法返回地址、附加信息等。
栈内存默认最大是1M,超出则抛出StackOverflowError。

(4)本地方法栈

和虚拟机栈功能类似,本地方法栈是为了虚拟机使用Native本地方法而准备的。
虚拟机规范没有规定具体的实现,由不同的虚拟机厂商去实现。
HotSpot虚拟机中虚拟机栈和本地方法栈的实现式一样的。同样,超出大小以后会抛出StackOverflowError。

(5)程序计数器(Program Counter Register)

记录当前线程执行字节码的位置,存储的是字节码指令地址,如果执行Native方法,则计数器值空。
每个线程都在这个空间有一个私有的空间,占用内存空间很少。
CPU同一时间,只会执行一条线程中的指令。JVM多线程会轮流切换并分配CPU执行时间的方式。为了线程切换后,需要通过程序计数器,来恢复正确的执行位置。
线程独占空间。

3.程序完成运行分析

public class Demo1{
    public static void main(String[] args){
        int x = 500;
        int y = 100;
        int a = x / y;
        int b = 50;
        System.out.println(a + b);
    }
}

(1)分析一

加载信息到方法区
HotSpot虚拟机:
1.7和之前称为永久代;1.8开始称为元数据空间
在这里插入图片描述

(2)分析二

jvm创建线程来执行代码
在虚拟机栈、程序计数器、内存区域中创建线程独占空间。
在这里插入图片描述

(3)分析三

在这里插入图片描述
【小结】
jvm运行原理中更底层实现,针对不同的操作系统或处理器,会有不同的实现。
这也就是Java能实现“一处编写,到处运行”的原因。

1.1.2线程状态

1.线程状态

在这里插入图片描述

2.状态转换图

在这里插入图片描述

3.代码示例

/**
*  多线程运行状态切换 <br/>
*/
public class Demo2 {
       public static Thread thread1;
       public static Demo2 obj;
       public static void main(String[] args) throws Exception {
              // 第一种状态切换 - 新建 -> 运行 -> 终止
              System.out.println("#######第一种状态切换  - 新建 -> 运行 -> 终止################################");
              Thread thread1 = new Thread(new Runnable() {
                     @Override
                     public void run() {
                           System.out.println("thread1当前状态:" +  Thread.currentThread().getState().toString());
                           System.out.println("thread1 执行了");
                     }
              });
              System.out.println("没调用start方法,thread1当前状态:" +  thread1.getState().toString());
              thread1.start();
              Thread.sleep(2000L); // 等待thread1执行结束,再看状态
              System.out.println("等待两秒,再看thread1当前状态:" +  thread1.getState().toString());
              // thread1.start(); TODO 注意,线程终止之后,再进行调用,会抛出IllegalThreadStateException异常
              System.out.println();
              System.out.println("############第二种:新建 -> 运行 -> 等待 -> 运行 ->  终止(sleep方式)###########################");
              Thread thread2 = new Thread(new Runnable() {
                     @Override
                     public void run() {
                           try {// 将线程2移动到等待状态,1500后自动唤醒
                                  Thread.sleep(1500);
                           } catch (InterruptedException e) {
                                  e.printStackTrace();
                           }
                           System.out.println("thread2当前状态:" +  Thread.currentThread().getState().toString());
                           System.out.println("thread2 执行了");
                     }
              });
              System.out.println("没调用start方法,thread2当前状态:" +  thread2.getState().toString());
              thread2.start();
              System.out.println("调用start方法,thread2当前状态:" +  thread2.getState().toString());
              Thread.sleep(200L); // 等待200毫秒,再看状态
              System.out.println("等待200毫秒,再看thread2当前状态:" +  thread2.getState().toString());
              Thread.sleep(3000L); // 再等待3秒,让thread2执行完毕,再看状态
              System.out.println("等待3秒,再看thread2当前状态:" +  thread2.getState().toString());
              System.out.println();
              System.out.println("############第三种:新建 -> 运行 -> 阻塞 -> 运行 ->  终止###########################");
              Thread thread3 = new Thread(new Runnable() {
                     @Override
                     public void run() {
                           synchronized (Demo2.class) {
                                  System.out.println("thread3当前状态:" +  Thread.currentThread().getState().toString());
                                  System.out.println("thread3 执行了");
                           }
                     }
              });
              synchronized (Demo2.class) {
                     System.out.println("没调用start方法,thread3当前状态:" +  thread3.getState().toString());
                     thread3.start();
                     System.out.println("调用start方法,thread3当前状态:" +  thread3.getState().toString());
                     Thread.sleep(200L); // 等待200毫秒,再看状态
                     System.out.println("等待200毫秒,再看thread3当前状态:" +  thread3.getState().toString());
              }
              Thread.sleep(3000L); // 再等待3秒,让thread3执行完毕,再看状态
              System.out.println("等待3秒,让thread3抢到锁,再看thread3当前状态:" +  thread2.getState().toString());
       }
}

1.1.3线程中止

1.不正确的线程中止-Stop

Stop:中止线程,并且清除监控锁的信息,但是可能到最后导致线程安全的问题,JDK不建议用。
Destory:JDK未实现该方法。

/**
* 示例3 - 线程stop强制性中止,破坏线程安全的示例
*/
public class Demo3 {
  public static void main(String[] args) throws InterruptedException {
    StopThread thread = new StopThread();
    thread.start();
    // 休眠1秒,确保i变量自增成功
    Thread.sleep(1000);
    // 暂停线程
    thread.stop(); // 错误的终止
    // thread.interrupt(); // 正确终止
    while (thread.isAlive()) {
      // 确保线程已经终止
    } // 输出结果
    thread.print();
  }
}
public class StopThread extends Thread {
  private int i = 0, j = 0;
  @Override
  public void run() {
    synchronized (this) {
           // 增加同步锁,确保线程安全
           ++i;
           try {
             // 休眠10秒,模拟耗时操作
             Thread.sleep(10000);
           } catch (InterruptedException e) {
             e.printStackTrace();
           }
           ++j;
    }
  }
  /** * 打印i和j */
  public void print() {
  System.out.println("i=" + i + " j=" + j);
  }
}

在这里插入图片描述
理想输出:i=0,j=0
程序运行结果:i=1,j=0
没有保证同步代码块里面数据一致性,破坏了线程安全

2.正确的线程中止-interrupt

(1)中止应用的条件

在这里插入图片描述

(2)代码示例

/**
* 示例3 - 线程stop强制性中止,破坏线程安全的示例
*/
public class Demo3 {
  public static void main(String[] args) throws InterruptedException {
    StopThread thread = new StopThread();
    thread.start();
    // 休眠1秒,确保i变量自增成功
    Thread.sleep(1000);
    // 暂停线程
    // thread.stop(); // 错误的终止
    thread.interrupt(); // 正确终止
    while (thread.isAlive()) {
      // 确保线程已经终止
    } // 输出结果
    thread.print();
  }
}

程序运行结果:i=1,j=1,数据一致。

3.正确的线程中止-标志位

代码逻辑中增加一个判断,来控制线程执行的中止。

/** 通过状态位来判断 */
public class Demo4 extends Thread {
  public volatile static boolean flag = true;
  public static void main(String[] args) throws InterruptedException {
    new Thread(() -> {
      try {
        while (flag) { // 判断是否运行
          System.out.println("运行中");
          Thread.sleep(1000L);
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
    // 3秒之后,将状态标志改为False,代表不继续运行
    Thread.sleep(3000L);
    flag = false;
    System.out.println("程序运行结束");
  }
}

1.1.4内存屏障和CPU缓存

1.CPU性能优化手段-缓存

理想为了提高程序运行的性能,现代CPU在很多方面对程序进行了优化。
例如:CPU高速缓存。尽可能地避免处理器访问主内存的时间开销,处理器大多会利用缓存(cache)以提高性能。
在这里插入图片描述

2.多级缓存

CPU在读取数据时,先在L1中寻找,再从L2寻找,再从L3寻找,然后是内存,再后是外存储器。
在这里插入图片描述

3.缓存同步协议

在这里插入图片描述

4.CPU性能优化手段-运行时指令重排

(1)概念

在这里插入图片描述
在这里插入图片描述

(2) 两个问题:

在这里插入图片描述

(3)内存屏障(Memory Barrier)

在这里插入图片描述
【小结】
现代CPU不断演进,在程序运行优化中做出的努力,不同CPU厂商所投入的人力物力成本,最终体现在不同CPU性能差距上。

1.1.5线程通信

1.线程通信的方式

要想实现多个线程之间的协同,如:线程执行先后顺序、获取某个线程执行的结构等等。涉及到线程之间相互通信,分为以下四类:

(1)文件共享

在这里插入图片描述
在这里插入图片描述

(2)网络共享

和文件共享类似。

(3)变量共享

在这里插入图片描述
在这里插入图片描述

(4)jdk提供的线程协调API

细分为:wait/notify、 park/unpark
JDK中对于需要多线程协作完成某一任务的场景,提供了对应API支持。
多线程写作典型场景是:生产者-消费者模型。(线程阻塞、线程唤醒)
【示例】
线程1去买包子,没有包子则不再执行。线程2生产出包子,通知线程1继续执行。
在这里插入图片描述

①API被弃用的suspend和resume

作用:调用suspend挂起目标线程,通过resume可以恢复线程执行。
被弃用的原因:容易出现死锁的代码。(在同步代码块中、先后顺序写错了都会造成死锁)
所以用wait/notify和park/unpark机制对它进行代替。
在这里插入图片描述

②wait/notify机制

在这里插入图片描述

③park/unpark机制

线程调用park 则等待“许可”,unpark方法为指定线程提供“许可(permit)”。
在这里插入图片描述

package com.study.hc.thread.chapter1.thread;
import java.util.concurrent.locks.LockSupport;
/** 三种线程协作通信的方式:suspend/resume、wait/notify、park/unpark */
public class Demo6 {
       /** 包子店 */
       public static Object baozidian = null;
       /** 正常的suspend/resume */
       public void suspendResumeTest() throws Exception {
              // 启动线程
              Thread consumerThread = new Thread(() -> {
                     if (baozidian == null) { // 如果没包子,则进入等待
                           System.out.println("1、进入等待");
                           Thread.currentThread().suspend();
                     }
                     System.out.println("2、买到包子,回家");
              });
              consumerThread.start();
              // 3秒之后,生产一个包子
              Thread.sleep(3000L);
              baozidian = new Object();
              consumerThread.resume();
              System.out.println("3、通知消费者");
       }
       /** 死锁的suspend/resume。 suspend并不会像wait一样释放锁,故此容易写出死锁代码  */
       public void suspendResumeDeadLockTest() throws Exception {
              // 启动线程
              Thread consumerThread = new Thread(() -> {
                     if (baozidian == null) { // 如果没包子,则进入等待
                           System.out.println("1、进入等待");
                           // 当前线程拿到锁,然后挂起
                           synchronized (this) {
                                  Thread.currentThread().suspend();
                           }
                     }
                     System.out.println("2、买到包子,回家");
              });
              consumerThread.start();
              // 3秒之后,生产一个包子
              Thread.sleep(3000L);
              baozidian = new Object();
              // 争取到锁以后,再恢复consumerThread
              synchronized (this) {
                     consumerThread.resume();
              }
              System.out.println("3、通知消费者");
       }
       /** 导致程序永久挂起的suspend/resume */
       public void suspendResumeDeadLockTest2() throws Exception {
              // 启动线程
              Thread consumerThread = new Thread(() -> {
                     if (baozidian == null) {
                           System.out.println("1、没包子,进入等待");
                           try { // 为这个线程加上一点延时
                                  Thread.sleep(5000L);
                           } catch (InterruptedException e) {
                                  e.printStackTrace();
                           }
                           // 这里的挂起执行在resume后面
                           Thread.currentThread().suspend();
                     }
                     System.out.println("2、买到包子,回家");
              });
              consumerThread.start();
              // 3秒之后,生产一个包子
              Thread.sleep(3000L);
              baozidian = new Object();
              consumerThread.resume();
              System.out.println("3、通知消费者");
              consumerThread.join();
       }
       /** 正常的wait/notify */
       public void waitNotifyTest() throws Exception {
              // 启动线程
              new Thread(() -> {
                           synchronized (this) {
                                  while (baozidian == null) { // 如果没包子,则进入等待
                                  try {
                                         System.out.println("1、进入等待");
                                         this.wait();
                                  } catch (InterruptedException e) {
                                         e.printStackTrace();
                                  }
                           }
                     }
                     System.out.println("2、买到包子,回家");
              }).start();
              // 3秒之后,生产一个包子
              Thread.sleep(3000L);
              baozidian = new Object();
              synchronized (this) {
                     this.notifyAll();
                     System.out.println("3、通知消费者");
              }
       }
       /** 会导致程序永久等待的wait/notify */
       public void waitNotifyDeadLockTest() throws Exception {
              // 启动线程
              new Thread(() -> {
                     if (baozidian == null) { // 如果没包子,则进入等待
                           try {
                                  Thread.sleep(5000L);
                           } catch (InterruptedException e1) {
                                  e1.printStackTrace();
                           }
                           synchronized (this) {
                                  try {
                                         System.out.println("1、进入等待");
                                         this.wait();
                                  } catch (InterruptedException e) {
                                         e.printStackTrace();
                                  }
                           }
                     }
                     System.out.println("2、买到包子,回家");
              }).start();
              // 3秒之后,生产一个包子
              Thread.sleep(3000L);
              baozidian = new Object();
              synchronized (this) {
                     this.notifyAll();
                     System.out.println("3、通知消费者");
              }
       }
       /** 正常的park/unpark */
       public void parkUnparkTest() throws Exception {
              // 启动线程
              Thread consumerThread = new Thread(() -> {
                     while (baozidian == null) { // 如果没包子,则进入等待
                           System.out.println("1、进入等待");
                           LockSupport.park();
                     }
                     System.out.println("2、买到包子,回家");
              });
              consumerThread.start();
              // 3秒之后,生产一个包子
              Thread.sleep(3000L);
              baozidian = new Object();
              LockSupport.unpark(consumerThread);
              System.out.println("3、通知消费者");
       }
       /** 死锁的park/unpark */
       public void parkUnparkDeadLockTest() throws Exception {
              // 启动线程
              Thread consumerThread = new Thread(() -> {
                     if (baozidian == null) { // 如果没包子,则进入等待
                           System.out.println("1、进入等待");
                           // 当前线程拿到锁,然后挂起
                           synchronized (this) {
                                  LockSupport.park();
                           }
                     }
                     System.out.println("2、买到包子,回家");
              });
              consumerThread.start();
              // 3秒之后,生产一个包子
              Thread.sleep(3000L);
              baozidian = new Object();
              // 争取到锁以后,再恢复consumerThread
              synchronized (this) {
                     LockSupport.unpark(consumerThread);
              }
              System.out.println("3、通知消费者");
       }
       public static void main(String[] args) throws Exception {
              // 对调用顺序有要求,也要开发自己注意锁的释放。这个被弃用的API, 容易死锁,也容易导致永久挂起。
//             new Demo6().suspendResumeTest();
//             new Demo6().suspendResumeDeadLockTest();
//             new Demo6().suspendResumeDeadLockTest2();
              // wait/notify要求再同步关键字里面使用,免去了死锁的困扰,但是一定要先调用wait,再调用notify,否则永久等待了
              // new Demo6().waitNotifyTest();
//             new Demo6().waitNotifyDeadLockTest();
              // park/unpark没有顺序要求,但是park并不会释放锁,所有再同步代码中使用要注意
//             new Demo6().parkUnparkTest();
               new Demo6().parkUnparkDeadLockTest();
       }
}
【三者对比】

对于调用顺序有要求,也要开发自己注意锁的释放,这个被弃用的API,容易死锁,也容易导致永久挂起。
wait/notify要求在同步关键字(synchronized)里使用,免去了死锁的困扰,但是一定要先调用wait,再调用notify,否则等待久了。
park/unpark没有顺序要求,但是park并不会释放锁,所以在同步代码块中使用要注意。

【伪唤醒】

在这里插入图片描述
在这里插入图片描述

【小结】

JDK多线程开发工具类,它是底层实现的原理。

1.1.6线程封闭概念

1.概念

在这里插入图片描述

2.ThreadLocal

在这里插入图片描述
可以理解为,JVM维护了一个Map<Thread,T>,每个线程都要用这个T的时候,用当前的线程去Map里面取。

package com.study.hc.thread.chapter1.thread;
/** 线程封闭示例 */
public class Demo7 {
       /** threadLocal变量,每个线程都有一个副本,互不干扰 */
       public static ThreadLocal<String> value = new ThreadLocal<>();
       /**
        * threadlocal测试
        *
        * @throws Exception
        */
       public void threadLocalTest() throws Exception {
              // threadlocal线程封闭示例
              value.set("这是主线程设置的123"); // 主线程设置值
              String v = value.get();
              System.out.println("线程1执行之前,主线程取到的值:" + v);
              new Thread(new Runnable() {
                     @Override
                     public void run() {
                           String v = value.get();
                           System.out.println("线程1取到的值:" + v);
                           // 设置 threadLocal
                           value.set("这是线程1设置的456");
                           v = value.get();
                           System.out.println("重新设置之后,线程1取到的值:" + v);
                           System.out.println("线程1执行结束");
                     }
              }).start();
              Thread.sleep(5000L); // 等待所有线程执行结束
              v = value.get();
              System.out.println("线程1执行之后,主线程取到的值:" + v);
       }
       public static void main(String[] args) throws Exception {
              new Demo7().threadLocalTest();
       }
}

运行结果:

3.栈封闭

在这里插入图片描述

1.1.7线程池原理

1.线程是不是越多越好

在这里插入图片描述

2.线程池原理-概念

在这里插入图片描述
在这里插入图片描述

3.线程池API-接口定义和实现类

可以认为ScheduledThreadPoolExecutor是最丰富的实现类。

4.线程池API-方法定义

(1)EexcutorService

在这里插入图片描述

(2)ScheduledEexcutorService

在这里插入图片描述

5.线程池API-Executors工具类

在这里插入图片描述

6.线程池原理-任务execute过程

在这里插入图片描述
在这里插入图片描述

package com.study.hc.thread.chapter1.thread;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/** 线程池的使用 */
public class Demo9 {
       /**
        * 测试: 提交15个执行时间需要3秒的任务,看线程池的状况
        *
        * @param threadPoolExecutor 传入不同的线程池,看不同的结果
        * @throws Exception
        */
       public void testCommon(ThreadPoolExecutor threadPoolExecutor) throws  Exception {
              // 测试: 提交15个执行时间需要3秒的任务,看超过大小的2个,对应的处理情况
              for (int i = 0; i < 15; i++) {
                     int n = i;
                     threadPoolExecutor.submit(new Runnable() {
                           @Override
                           public void run() {
                                  try {
                                         System.out.println("开始执行:" + n);
                                         Thread.sleep(3000L);
                                         System.err.println("执行结束:" + n);
                                  } catch (InterruptedException e) {
                                         e.printStackTrace();
                                  }
                           }
                     });
                     System.out.println("任务提交成功 :" + i);
              }
              // 查看线程数量,查看队列等待数量
              Thread.sleep(500L);
              System.out.println("当前线程池线程数量为:" +  threadPoolExecutor.getPoolSize());
              System.out.println("当前线程池等待的数量为:" +  threadPoolExecutor.getQueue().size());
              // 等待15秒,查看线程数量和队列数量(理论上,会被超出核心线程数量的线程自动销毁)
              Thread.sleep(15000L);
              System.out.println("当前线程池线程数量为:" +  threadPoolExecutor.getPoolSize());
              System.out.println("当前线程池等待的数量为:" +  threadPoolExecutor.getQueue().size());
       }
       /**
        * 1、线程池信息: 核心线程数量5,最大数量10,无界队列,超出核心线程数量的线程存活时间:5秒, 指定拒绝策略的
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest1() throws Exception {
              ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,  5, TimeUnit.SECONDS,
                           new LinkedBlockingQueue<Runnable>());
              testCommon(threadPoolExecutor);
              // 预计结果:线程池线程数量为:5,超出数量的任务,其他的进入队列中等待被执行
       }
       /**
        * 2、 线程池信息: 核心线程数量5,最大数量10,队列大小3,超出核心线程数量的线程存活时间:5秒, 指定拒绝策略的
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest2() throws Exception {
              // 创建一个 核心线程数量为5,最大数量为10,等待队列最大是3 的线程池,也就是最大容纳13个任务。
              // 默认的策略是抛出RejectedExecutionException异常,java.util.concurrent.ThreadPoolExecutor.AbortPolicy
              ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,  5, TimeUnit.SECONDS,
                           new LinkedBlockingQueue<Runnable>(3), new  RejectedExecutionHandler() {
                                  @Override
                                  public void rejectedExecution(Runnable r,  ThreadPoolExecutor executor) {
                                         System.err.println("有任务被拒绝执行了");
                                  }
                           });
              testCommon(threadPoolExecutor);
              // 预计结果:
              // 1、 5个任务直接分配线程开始执行
              // 2、 3个任务进入等待队列
              // 3、 队列不够用,临时加开5个线程来执行任务(5秒没活干就销毁)
              // 4、 队列和线程池都满了,剩下2个任务,没资源了,被拒绝执行。
              // 5、 任务执行,5秒后,如果无任务可执行,销毁临时创建的5个线程
       }
       /**
        * 3、 线程池信息: 核心线程数量5,最大数量5,无界队列,超出核心线程数量的线程存活时间:5秒
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest3() throws Exception {
              // 和Executors.newFixedThreadPool(int nThreads)一样的
              ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 5,  0L, TimeUnit.MILLISECONDS,
                           new LinkedBlockingQueue<Runnable>());
              testCommon(threadPoolExecutor);
              // 预计结:线程池线程数量为:5,超出数量的任务,其他的进入队列中等待被执行
       }
       /**
        * 4、 线程池信息:
        * 核心线程数量0,最大数量Integer.MAX_VALUE,SynchronousQueue队列,超出核心线程数量的线程存活时间:60秒
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest4() throws Exception {
              // SynchronousQueue,实际上它不是一个真正的队列,因为它不会为队列中元素维护存储空间。与其他队列不同的是,它维护一组线程,这些线程在等待着把元素加入或移出队列。
              // 在使用SynchronousQueue作为工作队列的前提下,客户端代码向线程池提交任务时,
              // 而线程池中又没有空闲的线程能够从SynchronousQueue队列实例中取一个任务,
              // 那么相应的offer方法调用就会失败(即任务没有被存入工作队列)。
              // 此时,ThreadPoolExecutor会新建一个新的工作者线程用于对这个入队列失败的任务进行处理(假设此时线程池的大小还未达到其最大线程池大小maximumPoolSize)。
              // 和Executors.newCachedThreadPool()一样的
              ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0,  Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                           new SynchronousQueue<Runnable>());
              testCommon(threadPoolExecutor);
              // 预计结果:
              // 1、 线程池线程数量为:15,超出数量的任务,其他的进入队列中等待被执行
              // 2、 所有任务执行结束,60秒后,如果无任务可执行,所有线程全部被销毁,池的大小恢复为0
              Thread.sleep(60000L);
              System.out.println("60秒后,再看线程池中的数量:" +  threadPoolExecutor.getPoolSize());
       }
       /**
        * 5、 定时执行线程池信息:3秒后执行,一次性任务,到点就执行 <br/>
        * 核心线程数量5,最大数量Integer.MAX_VALUE,DelayedWorkQueue延时队列,超出核心线程数量的线程存活时间:0秒
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest5() throws Exception {
              // 和Executors.newScheduledThreadPool()一样的
              ScheduledThreadPoolExecutor threadPoolExecutor = new  ScheduledThreadPoolExecutor(5);
              threadPoolExecutor.schedule(new Runnable() {
                     @Override
                     public void run() {
                           System.out.println("任务被执行,现在时间:" +  System.currentTimeMillis());
                     }
              }, 3000, TimeUnit.MILLISECONDS);
              System.out.println(
                           "定时任务,提交成功,时间是:" +  System.currentTimeMillis() + ", 当前线程池中线程数量:" +  threadPoolExecutor.getPoolSize());
              // 预计结果:任务在3秒后被执行一次
       }
       /**
        * 6、 定时执行线程池信息:线程固定数量5 ,<br/>
        * 核心线程数量5,最大数量Integer.MAX_VALUE,DelayedWorkQueue延时队列,超出核心线程数量的线程存活时间:0秒
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest6() throws Exception {
              ScheduledThreadPoolExecutor threadPoolExecutor = new  ScheduledThreadPoolExecutor(5);
              // 周期性执行某一个任务,线程池提供了两种调度方式,这里单独演示一下。测试场景一样。
              // 测试场景:提交的任务需要3秒才能执行完毕。看两种不同调度方式的区别
              // 效果1: 提交后,2秒后开始第一次执行,之后每间隔1秒,固定执行一次(如果发现上次执行还未完毕,则等待完毕,完毕后立刻执行)。
              // 也就是说这个代码中是,3秒钟执行一次(计算方式:每次执行三秒,间隔时间1秒,执行结束后马上开始下一次执行,无需等待)
              threadPoolExecutor.scheduleAtFixedRate(new Runnable() {
                     @Override
                     public void run() {
                           try {
                                  Thread.sleep(3000L);
                           } catch (InterruptedException e) {
                                  e.printStackTrace();
                           }
                           System.out.println("任务-1 被执行,现在时间:" +  System.currentTimeMillis());
                     }
              }, 2000, 1000, TimeUnit.MILLISECONDS);
              // 效果2:提交后,2秒后开始第一次执行,之后每间隔1秒,固定执行一次(如果发现上次执行还未完毕,则等待完毕,等上一次执行完毕后再开始计时,等待1秒)。
              // 也就是说这个代码钟的效果看到的是:4秒执行一次。 (计算方式:每次执行3秒,间隔时间1秒,执行完以后再等待1秒,所以是 3+1)
              threadPoolExecutor.scheduleWithFixedDelay(new Runnable() {
                     @Override
                     public void run() {
                           try {
                                  Thread.sleep(3000L);
                           } catch (InterruptedException e) {
                                  e.printStackTrace();
                           }
                           System.out.println("任务-2 被执行,现在时间:" +  System.currentTimeMillis());
                     }
              }, 2000, 1000, TimeUnit.MILLISECONDS);
       }
       /**
        * 7、 终止线程:线程池信息: 核心线程数量5,最大数量10,队列大小3,超出核心线程数量的线程存活时间:5秒, 指定拒绝策略的
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest7() throws Exception {
              // 创建一个 核心线程数量为5,最大数量为10,等待队列最大是3 的线程池,也就是最大容纳13个任务。
              // 默认的策略是抛出RejectedExecutionException异常,java.util.concurrent.ThreadPoolExecutor.AbortPolicy
              ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,  5, TimeUnit.SECONDS,
                           new LinkedBlockingQueue<Runnable>(3), new  RejectedExecutionHandler() {
                                  @Override
                                  public void rejectedExecution(Runnable r,  ThreadPoolExecutor executor) {
                                         System.err.println("有任务被拒绝执行了");
                                  }
                           });
              // 测试: 提交15个执行时间需要3秒的任务,看超过大小的2个,对应的处理情况
              for (int i = 0; i < 15; i++) {
                     int n = i;
                     threadPoolExecutor.submit(new Runnable() {
                           @Override
                           public void run() {
                                  try {
                                         System.out.println("开始执行:" + n);
                                         Thread.sleep(3000L);
                                         System.err.println("执行结束:" + n);
                                  } catch (InterruptedException e) {
                                         System.out.println("异常:" +  e.getMessage());
                                  }
                           }
                     });
                     System.out.println("任务提交成功 :" + i);
              }
              // 1秒后终止线程池
              Thread.sleep(1000L);
              threadPoolExecutor.shutdown();
              // 再次提交提示失败
              threadPoolExecutor.submit(new Runnable() {
                     @Override
                     public void run() {
                           System.out.println("追加一个任务");
                     }
              });
              // 结果分析
              // 1、 10个任务被执行,3个任务进入队列等待,2个任务被拒绝执行
              // 2、调用shutdown后,不接收新的任务,等待13任务执行结束
              // 3、 追加的任务在线程池关闭后,无法再提交,会被拒绝执行
       }
       /**
        * 8、 立刻终止线程:线程池信息: 核心线程数量5,最大数量10,队列大小3,超出核心线程数量的线程存活时间:5秒, 指定拒绝策略的
        *
        * @throws Exception
        */
       private void threadPoolExecutorTest8() throws Exception {
              // 创建一个 核心线程数量为5,最大数量为10,等待队列最大是3 的线程池,也就是最大容纳13个任务。
              // 默认的策略是抛出RejectedExecutionException异常,java.util.concurrent.ThreadPoolExecutor.AbortPolicy
              ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,  5, TimeUnit.SECONDS,
                           new LinkedBlockingQueue<Runnable>(3), new  RejectedExecutionHandler() {
                                  @Override
                                  public void rejectedExecution(Runnable r,  ThreadPoolExecutor executor) {
                                         System.err.println("有任务被拒绝执行了");
                                  }
                           });
              // 测试: 提交15个执行时间需要3秒的任务,看超过大小的2个,对应的处理情况
              for (int i = 0; i < 15; i++) {
                     int n = i;
                     threadPoolExecutor.submit(new Runnable() {
                           @Override
                           public void run() {
                                  try {
                                         System.out.println("开始执行:" + n);
                                         Thread.sleep(3000L);
                                         System.err.println("执行结束:" + n);
                                  } catch (InterruptedException e) {
                                         System.out.println("异常:" +  e.getMessage());
                                  }
                           }
                     });
                     System.out.println("任务提交成功 :" + i);
              }
              // 1秒后终止线程池
              Thread.sleep(1000L);
              List<Runnable> shutdownNow = threadPoolExecutor.shutdownNow();
              // 再次提交提示失败
              threadPoolExecutor.submit(new Runnable() {
                     @Override
                     public void run() {
                           System.out.println("追加一个任务");
                     }
              });
              System.out.println("未结束的任务有:" + shutdownNow.size());
              // 结果分析
              // 1、 10个任务被执行,3个任务进入队列等待,2个任务被拒绝执行
              // 2、调用shutdownnow后,队列中的3个线程不再执行,10个线程被终止
              // 3、 追加的任务在线程池关闭后,无法再提交,会被拒绝执行
       }
       public static void main(String[] args) throws Exception {
//            new Demo9().threadPoolExecutorTest1();
//            new Demo9().threadPoolExecutorTest2();
//            new Demo9().threadPoolExecutorTest3();
//            new Demo9().threadPoolExecutorTest4();
//            new Demo9().threadPoolExecutorTest5();
//            new Demo9().threadPoolExecutorTest6();
//            new Demo9().threadPoolExecutorTest7();
              new Demo9().threadPoolExecutorTest8();
       }
}

7.线程数量

如何确定合适数量的线程?
在这里插入图片描述

如果CPU使用率=80%比较合适。
<80%说明没有充分利用;
80%:线程太多了,CPU处理不过来

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值