# 多线程与反射
前面我们已经讲解了 JavaSE 的大部分核心内容,最后一章,我们还将继续学习 JavaSE 中提供的各种高级特性。这些高级特性对于我们之后的学习,会有着举足轻重的作用。
# 多线程
** 注意:** 本章节会涉及到 操作系统 相关知识。
在了解多线程之前,让我们回顾一下 操作系统
中提到的进程概念:
进程是程序执行的实体,每一个进程都是一个应用程序(比如我们运行 QQ、浏览器、LOL、网易云音乐等软件),都有自己的内存空间,CPU 一个核心同时只能处理一件事情,当出现多个进程需要同时运行时,CPU 一般通过 时间片轮转调度
算法,来实现多个进程的同时运行。
在早期的计算机中,进程是拥有资源和独立运行的最小单位,也是程序执行的最小单位。但是,如果我希望两个任务同时进行,就必须运行两个进程,由于每个进程都有一个自己的内存空间,进程之间的通信就变得非常麻烦(比如要共享某些数据)而且执行不同进程会产生上下文切换,非常耗时,那么能否实现在一个进程中就能够执行多个任务呢?
后来,线程横空出世,一个进程可以有多个线程,线程是程序执行中一个单一的顺序控制流程,现在线程才是程序执行流的最小单元,各个线程之间共享程序的内存空间(也就是所在进程的内存空间),上下文切换速度也高于进程。
在 Java 中,我们从开始,一直以来编写的都是单线程应用程序(运行 main()
方法的内容),也就是说只能同时执行一个任务(无论你是调用方法、还是进行计算,始终都是依次进行的,也就是同步的),而如果我们希望同时执行多个任务(两个方法同时在运行或者是两个计算同时在进行,也就是异步的),就需要用到 Java 多线程框架。实际上一个 Java 程序启动后,会创建很多线程,不仅仅只运行一个主线程:
public static void main(String[] args) { | |
ThreadMXBean bean = ManagementFactory.getThreadMXBean(); | |
long[] ids = bean.getAllThreadIds(); | |
ThreadInfo[] infos = bean.getThreadInfo(ids); | |
for (ThreadInfo info : infos) { | |
System.out.println(info.getThreadName()); | |
} | |
} |
关于除了 main 线程默认以外的线程,涉及到 JVM 相关底层原理,在这里不做讲解,了解就行。
# 线程的创建和启动
通过创建 Thread 对象来创建一个新的线程,Thread 构造方法中需要传入一个 Runnable 接口的实现(其实就是编写要在另一个线程执行的内容逻辑)同时 Runnable 只有一个未实现方法,因此可以直接使用 lambda 表达式:
@FunctionalInterface | |
public interface Runnable { | |
/** | |
* When an object implementing interface <code>Runnable</code> is used | |
* to create a thread, starting the thread causes the object's | |
* <code>run</code> method to be called in that separately executing | |
* thread. | |
* <p> | |
* The general contract of the method <code>run</code> is that it may | |
* take any action whatsoever. | |
* | |
* @see java.lang.Thread#run() | |
*/ | |
public abstract void run(); | |
} |
创建好后,通过调用 start()
方法来运行此线程:
public static void main(String[] args) { | |
Thread t = new Thread(() -> { // 直接编写逻辑 | |
System.out.println("我是另一个线程!"); | |
}); | |
t.start(); // 调用此方法来开始执行此线程 | |
} |
可能上面的例子看起来和普通的单线程没两样,那我们先来看看下面这段代码的运行结果:
public static void main(String[] args) { | |
Thread t = new Thread(() -> { | |
System.out.println("我是线程:"+Thread.currentThread().getName()); | |
System.out.println("我正在计算 0-10000 之间所有数的和..."); | |
int sum = 0; | |
for (int i = 0; i <= 10000; i++) { | |
sum += i; | |
} | |
System.out.println("结果:"+sum); | |
}); | |
t.start(); | |
System.out.println("我是主线程!"); | |
} |
我们发现,这段代码执行输出结果并不是按照从上往下的顺序了,因为他们分别位于两个线程,他们是同时进行的!如果你还是觉得很疑惑,我们接着来看下面的代码运行结果:
public static void main(String[] args) { | |
Thread t1 = new Thread(() -> { | |
for (int i = 0; i < 50; i++) { | |
System.out.println("我是一号线程:"+i); | |
} | |
}); | |
Thread t2 = new Thread(() -> { | |
for (int i = 0; i < 50; i++) { | |
System.out.println("我是二号线程:"+i); | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
} |
我们可以看到打印实际上是在交替进行的,也证明了他们是在同时运行!
注意:我们发现还有一个 run 方法,也能执行线程里面定义的内容,但是 run 是直接在当前线程执行,并不是创建一个线程执行!
实际上,线程和进程差不多,也会等待获取 CPU 资源,一旦获取到,就开始按顺序执行我们给定的程序,当需要等待外部 IO 操作(比如 Scanner 获取输入的文本),就会暂时处于休眠状态,等待通知,或是调用 sleep()
方法来让当前线程休眠一段时间:
public static void main(String[] args) throws InterruptedException { | |
System.out.println("l"); | |
Thread.sleep(1000); // 休眠时间,以毫秒为单位,1000ms = 1s | |
System.out.println("b"); | |
Thread.sleep(1000); | |
System.out.println("w"); | |
Thread.sleep(1000); | |
System.out.println("nb!"); | |
} |
我们也可以使用 stop()
方法来强行终止此线程:
public static void main(String[] args) throws InterruptedException { | |
Thread t = new Thread(() -> { | |
Thread me = Thread.currentThread(); // 获取当前线程对象 | |
for (int i = 0; i < 50; i++) { | |
System.out.println("打印:"+i); | |
if(i == 20) me.stop(); // 此方法会直接终止此线程 | |
} | |
}); | |
t.start(); | |
} |
虽然 stop()
方法能够终止此线程,但是并不是所推荐的做法,有关线程中断相关问题,我们会在后面继续了解。
思考:猜猜以下程序输出结果:
private static int value = 0; | |
public static void main(String[] args) throws InterruptedException { | |
Thread t1 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) value++; | |
System.out.println("线程1完成"); | |
}); | |
Thread t2 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) value++; | |
System.out.println("线程2完成"); | |
}); | |
t1.start(); | |
t2.start(); | |
Thread.sleep(1000); // 主线程停止 1 秒,保证两个线程执行完成 | |
System.out.println(value); | |
} |
我们发现,value 最后的值并不是我们理想的结果,有关为什么会出现这种问题,在我们学习到线程锁的时候,再来探讨。
# 线程的休眠和中断
我们前面提到,一个线程处于运行状态下,线程的下一个状态会出现以下情况:
- 当 CPU 给予的运行时间结束时,会从运行状态回到就绪(可运行)状态,等待下一次获得 CPU 资源。
- 当线程进入休眠 / 阻塞 (如等待 IO 请求) / 手动调用
wait()
方法时,会使得线程处于等待状态,当等待状态结束后会回到就绪状态。 - 当线程出现异常或错误 / 被
stop()
方法强行停止 / 所有代码执行结束时,会使得线程的运行终止。
而这个部分我们着重了解一下线程的休眠和中断,首先我们来了解一下如何使得线程进如休眠状态:
public static void main(String[] args) { | |
Thread t = new Thread(() -> { | |
try { | |
System.out.println("l"); | |
Thread.sleep(1000); //sleep 方法是 Thread 的静态方法,它只作用于当前线程(它知道当前线程是哪个) | |
System.out.println("b"); // 调用 sleep 后,线程会直接进入到等待状态,直到时间结束 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}); | |
t.start(); | |
} |
通过调用 sleep()
方法来将当前线程进入休眠,使得线程处于等待状态一段时间。我们发现,此方法显示声明了会抛出一个 InterruptedException 异常,那么这个异常在什么时候会发生呢?
public static void main(String[] args) { | |
Thread t = new Thread(() -> { | |
try { | |
Thread.sleep(10000); // 休眠 10 秒 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}); | |
t.start(); | |
try { | |
Thread.sleep(3000); // 休眠 3 秒,一定比线程 t 先醒来 | |
t.interrupt(); // 调用 t 的 interrupt 方法 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} |
我们发现,每一个 Thread 对象中,都有一个 interrupt()
方法,调用此方法后,会给指定线程添加一个中断标记以告知线程需要立即停止运行或是进行其他操作,由线程来响应此中断并进行相应的处理,我们前面提到的 stop()
方法是强制终止线程,这样的做法虽然简单粗暴,但是很有可能导致资源不能完全释放,而类似这样的发送通知来告知线程需要中断,让线程自行处理后续,会更加合理一些,也是更加推荐的做法。我们来看看 interrupt 的用法:
public static void main(String[] args) { | |
Thread t = new Thread(() -> { | |
System.out.println("线程开始运行!"); | |
while (true){ // 无限循环 | |
if(Thread.currentThread().isInterrupted()){ // 判断是否存在中断标志 | |
break; // 响应中断 | |
} | |
} | |
System.out.println("线程被中断了!"); | |
}); | |
t.start(); | |
try { | |
Thread.sleep(3000); // 休眠 3 秒,一定比线程 t 先醒来 | |
t.interrupt(); // 调用 t 的 interrupt 方法 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} |
通过 isInterrupted()
可以判断线程是否存在中断标志,如果存在,说明外部希望当前线程立即停止,也有可能是给当前线程发送一个其他的信号,如果我们并不是希望收到中断信号就是结束程序,而是通知程序做其他事情,我们可以在收到中断信号后,复位中断标记,然后继续做我们的事情:
public static void main(String[] args) { | |
Thread t = new Thread(() -> { | |
System.out.println("线程开始运行!"); | |
while (true){ | |
if(Thread.currentThread().isInterrupted()){ // 判断是否存在中断标志 | |
System.out.println("发现中断信号,复位,继续运行..."); | |
Thread.interrupted(); // 复位中断标记(返回值是当前是否有中断标记,这里不用管) | |
} | |
} | |
}); | |
t.start(); | |
try { | |
Thread.sleep(3000); // 休眠 3 秒,一定比线程 t 先醒来 | |
t.interrupt(); // 调用 t 的 interrupt 方法 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} |
复位中断标记后,会立即清除中断标记。那么,如果现在我们想暂停线程呢?我们希望线程暂时停下,比如等待其他线程执行完成后,再继续运行,那这样的操作怎么实现呢?
public static void main(String[] args) { | |
Thread t = new Thread(() -> { | |
System.out.println("线程开始运行!"); | |
Thread.currentThread().suspend(); // 暂停此线程 | |
System.out.println("线程继续运行!"); | |
}); | |
t.start(); | |
try { | |
Thread.sleep(3000); // 休眠 3 秒,一定比线程 t 先醒来 | |
t.resume(); // 恢复此线程 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} |
虽然这样很方便地控制了线程的暂停状态,但是这两个方法我们发现实际上也是不推荐的做法,它很容易导致死锁!有关为什么被弃用的原因,我们会在线程锁继续探讨。
# 线程的优先级
实际上,Java 程序中的每个线程并不是平均分配 CPU 时间的,为了使得线程资源分配更加合理,Java 采用的是抢占式调度方式,优先级越高的线程,优先使用 CPU 资源!我们希望 CPU 花费更多的时间去处理更重要的任务,而不太重要的任务,则可以先让出一部分资源。线程的优先级一般分为以下三种:
- MIN_PRIORITY 最低优先级
- MAX_PRIORITY 最高优先级
- NOM_PRIORITY 常规优先级
public static void main(String[] args) { | |
Thread t = new Thread(() -> { | |
System.out.println("线程开始运行!"); | |
}); | |
t.start(); | |
t.setPriority(Thread.MIN_PRIORITY); // 通过使用 setPriority 方法来设定优先级 | |
} |
优先级越高的线程,获得 CPU 资源的概率会越大,并不是说一定优先级越高的线程越先执行!
# 线程的礼让和加入
我们还可以在当前线程的工作不重要时,将 CPU 资源让位给其他线程,通过使用 yield()
方法来将当前资源让位给其他同优先级线程:
public static void main(String[] args) { | |
Thread t1 = new Thread(() -> { | |
System.out.println("线程1开始运行!"); | |
for (int i = 0; i < 50; i++) { | |
if(i % 5 == 0) { | |
System.out.println("让位!"); | |
Thread.yield(); | |
} | |
System.out.println("1打印:"+i); | |
} | |
System.out.println("线程1结束!"); | |
}); | |
Thread t2 = new Thread(() -> { | |
System.out.println("线程2开始运行!"); | |
for (int i = 0; i < 50; i++) { | |
System.out.println("2打印:"+i); | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
} |
观察结果,我们发现,在让位之后,尽可能多的在执行线程 2 的内容。
当我们希望一个线程等待另一个线程执行完成后再继续进行,我们可以使用 join()
方法来实现线程的加入:
public static void main(String[] args) { | |
Thread t1 = new Thread(() -> { | |
System.out.println("线程1开始运行!"); | |
for (int i = 0; i < 50; i++) { | |
System.out.println("1打印:"+i); | |
} | |
System.out.println("线程1结束!"); | |
}); | |
Thread t2 = new Thread(() -> { | |
System.out.println("线程2开始运行!"); | |
for (int i = 0; i < 50; i++) { | |
System.out.println("2打印:"+i); | |
if(i == 10){ | |
try { | |
System.out.println("线程1加入到此线程!"); | |
t1.join(); // 在 i==10 时,让线程 1 加入,先完成线程 1 的内容,在继续当前内容 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
} |
我们发现,线程 1 加入后,线程 2 等待线程 1 待执行的内容全部执行完成之后,再继续执行的线程 2 内容。注意,线程的加入只是等待另一个线程的完成,并不是将另一个线程和当前线程合并!我们来看看:
public static void main(String[] args) { | |
Thread t1 = new Thread(() -> { | |
System.out.println(Thread.currentThread().getName()+"开始运行!"); | |
for (int i = 0; i < 50; i++) { | |
System.out.println(Thread.currentThread().getName()+"打印:"+i); | |
} | |
System.out.println("线程1结束!"); | |
}); | |
Thread t2 = new Thread(() -> { | |
System.out.println("线程2开始运行!"); | |
for (int i = 0; i < 50; i++) { | |
System.out.println("2打印:"+i); | |
if(i == 10){ | |
try { | |
System.out.println("线程1加入到此线程!"); | |
t1.join(); // 在 i==10 时,让线程 1 加入,先完成线程 1 的内容,在继续当前内容 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
} |
实际上,t2 线程只是暂时处于等待状态,当 t1 执行结束时,t2 才开始继续执行,只是在效果上看起来好像是两个线程合并为一个线程在执行而已。
# 线程锁和线程同步
在开始讲解线程同步之前,我们需要先了解一下多线程情况下 Java 的内存管理:
线程之间的共享变量(比如之前悬念中的 value 变量)存储在主内存(main memory)中,每个线程都有一个私有的工作内存(本地内存),工作内存中存储了该线程以读 / 写共享变量的副本。它类似于我们在 计算机组成原理
中学习的多核心处理器高速缓存机制:
高速缓存通过保存内存中数据的副本来提供更加快速的数据访问,但是如果多个处理器的运算任务都涉及同一块内存区域,就可能导致各自的高速缓存数据不一致,在写回主内存时就会发生冲突,这就是引入高速缓存引发的新问题,称之为:缓存一致性。
实际上,Java 的内存模型也是这样类似设计的,当我们同时去操作一个共享变量时,如果仅仅是读取还好,但是如果同时写入内容,就会出现问题!好比说一个银行,如果我和我的朋友同时在银行取我账户里面的钱,难道取 1000 还可能吐 2000 出来吗?我们需要一种更加安全的机制来维持秩序,保证数据的安全性!
比如我们可以来看看下面这个问题:
private static int value = 0; | |
public static void main(String[] args) throws InterruptedException { | |
Thread t1 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) value++; | |
System.out.println("线程1完成"); | |
}); | |
Thread t2 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) value++; | |
System.out.println("线程2完成"); | |
}); | |
t1.start(); | |
t2.start(); | |
Thread.sleep(1000); // 主线程停止 1 秒,保证两个线程执行完成 | |
System.out.println(value); | |
} |
实际上,当两个线程同时读取 value 的时候,可能会同时拿到同样的值,而进行自增操作之后,也是同样的值,再写回主内存后,本来应该进行 2 次自增操作,实际上只执行了一次!
通过 synchronized 关键字来创造一个线程锁,首先我们来认识一下 synchronized 代码块,它需要在括号中填入一个内容,必须是一个对象或是一个类,我们在 value 自增操作外套上同步代码块:
private static int value = 0; | |
public static void main(String[] args) throws InterruptedException { | |
Thread t1 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) { | |
synchronized (Main.class){ // 使用 synchronized 关键字创建同步代码块 | |
value++; | |
} | |
} | |
System.out.println("线程1完成"); | |
}); | |
Thread t2 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) { | |
synchronized (Main.class){ | |
value++; | |
} | |
} | |
System.out.println("线程2完成"); | |
}); | |
t1.start(); | |
t2.start(); | |
Thread.sleep(1000); // 主线程停止 1 秒,保证两个线程执行完成 | |
System.out.println(value); | |
} |
我们发现,现在得到的结果就是我们想要的内容了,因为在同步代码块执行过程中,拿到了我们传入对象或类的锁(传入的如果是对象,就是对象锁,不同的对象代表不同的对象锁,如果是类,就是类锁,类锁只有一个,实际上类锁也是对象锁,是 Class 类实例,但是 Class 类实例同样的类无论怎么获取都是同一个),但是注意两个线程必须使用同一把锁!
当一个线程进入到同步代码块时,会获取到当前的锁,而这时如果其他使用同样的锁的同步代码块也想执行内容,就必须等待当前同步代码块的内容执行完毕,在执行完毕后会自动释放这把锁,而其他的线程才能拿到这把锁并开始执行同步代码块里面的内容(实际上 synchronized 是一种悲观锁,随时都认为有其他线程在对数据进行修改,后面在 JUC 篇视频教程中我们还会讲到乐观锁,如 CAS 算法)
那么我们来看看,如果使用的是不同对象的锁,那么还能顺利进行吗?
private static int value = 0; | |
public static void main(String[] args) throws InterruptedException { | |
Main main1 = new Main(); | |
Main main2 = new Main(); | |
Thread t1 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) { | |
synchronized (main1){ | |
value++; | |
} | |
} | |
System.out.println("线程1完成"); | |
}); | |
Thread t2 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) { | |
synchronized (main2){ | |
value++; | |
} | |
} | |
System.out.println("线程2完成"); | |
}); | |
t1.start(); | |
t2.start(); | |
Thread.sleep(1000); // 主线程停止 1 秒,保证两个线程执行完成 | |
System.out.println(value); | |
} |
当对象不同时,获取到的是不同的锁,因此并不能保证自增操作的原子性,最后也得不到我们想要的结果。
synchronized 关键字也可以作用于方法上,调用此方法时也会获取锁:
private static int value = 0; | |
private static synchronized void add(){ | |
value++; | |
} | |
public static void main(String[] args) throws InterruptedException { | |
Thread t1 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) add(); | |
System.out.println("线程1完成"); | |
}); | |
Thread t2 = new Thread(() -> { | |
for (int i = 0; i < 10000; i++) add(); | |
System.out.println("线程2完成"); | |
}); | |
t1.start(); | |
t2.start(); | |
Thread.sleep(1000); // 主线程停止 1 秒,保证两个线程执行完成 | |
System.out.println(value); | |
} |
我们发现实际上效果是相同的,只不过这个锁不用你去给,如果是静态方法,就是使用的类锁,而如果是普通成员方法,就是使用的对象锁。通过灵活的使用 synchronized 就能很好地解决我们之前提到的问题了。
# 死锁
其实死锁的概念在 操作系统
中也有提及,它是指两个线程相互持有对方需要的锁,但是又迟迟不释放,导致程序卡住:
我们发现,线程 A 和线程 B 都需要对方的锁,但是又被对方牢牢把握,由于线程被无限期地阻塞,因此程序不可能正常终止。我们来看看以下这段代码会得到什么结果:
public static void main(String[] args) throws InterruptedException { | |
Object o1 = new Object(); | |
Object o2 = new Object(); | |
Thread t1 = new Thread(() -> { | |
synchronized (o1){ | |
try { | |
Thread.sleep(1000); | |
synchronized (o2){ | |
System.out.println("线程1"); | |
} | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
Thread t2 = new Thread(() -> { | |
synchronized (o2){ | |
try { | |
Thread.sleep(1000); | |
synchronized (o1){ | |
System.out.println("线程2"); | |
} | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
} |
所以,我们在编写程序时,一定要注意,不要出现这种死锁的情况。那么我们如何去检测死锁呢?我们可以利用 jstack 命令来检测死锁,首先利用 jps 找到我们的 java 进程:
nagocoler@NagodeMacBook-Pro ~ % jps | |
51592 Launcher | |
51690 Jps | |
14955 | |
51693 Main | |
nagocoler@NagodeMacBook-Pro ~ % jstack 51693 | |
... | |
Java stack information for the threads listed above: | |
=================================================== | |
"Thread-1": | |
at com.test.Main.lambda$main$1(Main.java:46) | |
- waiting to lock <0x000000076ad27fc0> (a java.lang.Object) | |
- locked <0x000000076ad27fd0> (a java.lang.Object) | |
at com.test.Main$$Lambda$2/1867750575.run(Unknown Source) | |
at java.lang.Thread.run(Thread.java:748) | |
"Thread-0": | |
at com.test.Main.lambda$main$0(Main.java:34) | |
- waiting to lock <0x000000076ad27fd0> (a java.lang.Object) | |
- locked <0x000000076ad27fc0> (a java.lang.Object) | |
at com.test.Main$$Lambda$1/396873410.run(Unknown Source) | |
at java.lang.Thread.run(Thread.java:748) | |
Found 1 deadlock. |
jstack 自动帮助我们找到了一个死锁,并打印出了相关线程的栈追踪信息,同样的,使用 jconsole
也可以进行监测。
因此,前面说不推荐使用 suspend()
去挂起线程的原因,是因为 suspend()
在使线程暂停的同时,并不会去释放任何锁资源。其他线程都无法访问被它占用的锁。直到对应的线程执行 resume()
方法后,被挂起的线程才能继续,从而其它被阻塞在这个锁的线程才可以继续执行。但是,如果 resume()
操作出现在 suspend()
之前执行,那么线程将一直处于挂起状态,同时一直占用锁,这就产生了死锁。
# wait 和 notify 方法
其实我们之前可能就发现了,Object 类还有三个方法我们从来没有使用过,分别是 wait()
、 notify()
以及 notifyAll()
,他们其实是需要配合 synchronized 来使用的(实际上锁就是依附于对象存在的,每个对象都应该有针对于锁的一些操作,所以说就这样设计了)当然,只有在同步代码块中才能使用这些方法,正常情况下会报错,我们来看看他们的作用是什么:
public static void main(String[] args) throws InterruptedException { | |
Object o1 = new Object(); | |
Thread t1 = new Thread(() -> { | |
synchronized (o1){ | |
try { | |
System.out.println("开始等待"); | |
o1.wait(); // 进入等待状态并释放锁 | |
System.out.println("等待结束!"); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
Thread t2 = new Thread(() -> { | |
synchronized (o1){ | |
System.out.println("开始唤醒!"); | |
o1.notify(); // 唤醒处于等待状态的线程 | |
for (int i = 0; i < 50; i++) { | |
System.out.println(i); | |
} | |
// 唤醒后依然需要等待这里的锁释放之前等待的线程才能继续 | |
} | |
}); | |
t1.start(); | |
Thread.sleep(1000); | |
t2.start(); | |
} |
我们可以发现,对象的 wait()
方法会暂时使得此线程进入等待状态,同时会释放当前代码块持有的锁,这时其他线程可以获取到此对象的锁,当其他线程调用对象的 notify()
方法后,会唤醒刚才变成等待状态的线程(这时并没有立即释放锁)。注意,必须是在持有锁(同步代码块内部)的情况下使用,否则会抛出异常!
notifyAll 其实和 notify 一样,也是用于唤醒,但是前者是唤醒所有调用 wait()
后处于等待的线程,而后者是看运气随机选择一个。
# ThreadLocal 的使用
既然每个线程都有一个自己的工作内存,那么能否只在自己的工作内存中创建变量仅供线程自己使用呢?
我们可以使用 ThreadLocal 类,来创建工作内存中的变量,它将我们的变量值存储在内部(只能存储一个变量),不同的线程访问到 ThreadLocal 对象时,都只能获取到当前线程所属的变量。
public static void main(String[] args) throws InterruptedException { | |
ThreadLocal<String> local = new ThreadLocal<>(); // 注意这是一个泛型类,存储类型为我们要存放的变量类型 | |
Thread t1 = new Thread(() -> { | |
local.set("lbwnb"); // 将变量的值给予 ThreadLocal | |
System.out.println("变量值已设定!"); | |
System.out.println(local.get()); // 尝试获取 ThreadLocal 中存放的变量 | |
}); | |
Thread t2 = new Thread(() -> { | |
System.out.println(local.get()); // 尝试获取 ThreadLocal 中存放的变量 | |
}); | |
t1.start(); | |
Thread.sleep(3000); // 间隔三秒 | |
t2.start(); | |
} |
上面的例子中,我们开启两个线程分别去访问 ThreadLocal 对象,我们发现,第一个线程存放的内容,第一个线程可以获取,但是第二个线程无法获取,我们再来看看第一个线程存入后,第二个线程也存放,是否会覆盖第一个线程存放的内容:
public static void main(String[] args) throws InterruptedException { | |
ThreadLocal<String> local = new ThreadLocal<>(); // 注意这是一个泛型类,存储类型为我们要存放的变量类型 | |
Thread t1 = new Thread(() -> { | |
local.set("lbwnb"); // 将变量的值给予 ThreadLocal | |
System.out.println("线程1变量值已设定!"); | |
try { | |
Thread.sleep(2000); // 间隔 2 秒 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("线程1读取变量值:"); | |
System.out.println(local.get()); // 尝试获取 ThreadLocal 中存放的变量 | |
}); | |
Thread t2 = new Thread(() -> { | |
local.set("yyds"); // 将变量的值给予 ThreadLocal | |
System.out.println("线程2变量值已设定!"); | |
}); | |
t1.start(); | |
Thread.sleep(1000); // 间隔 1 秒 | |
t2.start(); | |
} |
我们发现,即使线程 2 重新设定了值,也没有影响到线程 1 存放的值,所以说,不同线程向 ThreadLocal 存放数据,只会存放在线程自己的工作空间中,而不会直接存放到主内存中,因此各个线程直接存放的内容互不干扰。
我们发现在线程中创建的子线程,无法获得父线程工作内存中的变量:
public static void main(String[] args) { | |
ThreadLocal<String> local = new ThreadLocal<>(); | |
Thread t = new Thread(() -> { | |
local.set("lbwnb"); | |
new Thread(() -> { | |
System.out.println(local.get()); | |
}).start(); | |
}); | |
t.start(); | |
} |
我们可以使用 InheritableThreadLocal 来解决:
public static void main(String[] args) { | |
ThreadLocal<String> local = new InheritableThreadLocal<>(); | |
Thread t = new Thread(() -> { | |
local.set("lbwnb"); | |
new Thread(() -> { | |
System.out.println(local.get()); | |
}).start(); | |
}); | |
t.start(); | |
} |
在 InheritableThreadLocal 存放的内容,会自动向子线程传递。
# 定时器
我们有时候会有这样的需求,我希望定时执行任务,比如 3 秒后执行,其实我们可以通过使用 Thread.sleep()
来实现:
public static void main(String[] args) { | |
new TimerTask(() -> System.out.println("我是定时任务!"), 3000).start(); // 创建并启动此定时任务 | |
} | |
static class TimerTask{ | |
Runnable task; | |
long time; | |
public TimerTask(Runnable runnable, long time){ | |
this.task = runnable; | |
this.time = time; | |
} | |
public void start(){ | |
new Thread(() -> { | |
try { | |
Thread.sleep(time); | |
task.run(); // 休眠后再运行 | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}).start(); | |
} | |
} |
我们通过自行封装一个 TimerTask 类,并在启动时,先休眠 3 秒钟,再执行我们传入的内容。那么现在我们希望,能否循环执行一个任务呢?比如我希望每隔 1 秒钟执行一次代码,这样该怎么做呢?
public static void main(String[] args) { | |
new TimerLoopTask(() -> System.out.println("我是定时任务!"), 3000).start(); // 创建并启动此定时任务 | |
} | |
static class TimerLoopTask{ | |
Runnable task; | |
long loopTime; | |
public TimerLoopTask(Runnable runnable, long loopTime){ | |
this.task = runnable; | |
this.loopTime = loopTime; | |
} | |
public void start(){ | |
new Thread(() -> { | |
try { | |
while (true){ // 无限循环执行 | |
Thread.sleep(loopTime); | |
task.run(); // 休眠后再运行 | |
} | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}).start(); | |
} | |
} |
现在我们将单次执行放入到一个无限循环中,这样就能一直执行了,并且按照我们的间隔时间进行。
但是终究是我们自己实现,可能很多方面还没考虑到,Java 也为我们提供了一套自己的框架用于处理定时任务:
public static void main(String[] args) { | |
Timer timer = new Timer(); // 创建定时器对象 | |
timer.schedule(new TimerTask() { // 注意这个是一个抽象类,不是接口,无法使用 lambda 表达式简化,只能使用匿名内部类 | |
@Override | |
public void run() { | |
System.out.println(Thread.currentThread().getName()); // 打印当前线程名称 | |
} | |
}, 1000); // 执行一个延时任务 | |
} |
我们可以通过创建一个 Timer 类来让它进行定时任务调度,我们可以通过此对象来创建任意类型的定时任务,包延时任务、循环定时任务等。我们发现,虽然任务执行完成了,但是我们的程序并没有停止,这是因为 Timer 内存维护了一个任务队列和一个工作线程:
public class Timer { | |
/** | |
* The timer task queue. This data structure is shared with the timer | |
* thread. The timer produces tasks, via its various schedule calls, | |
* and the timer thread consumes, executing timer tasks as appropriate, | |
* and removing them from the queue when they're obsolete. | |
*/ | |
private final TaskQueue queue = new TaskQueue(); | |
/** | |
* The timer thread. | |
*/ | |
private final TimerThread thread = new TimerThread(queue); | |
... | |
} |
TimerThread 继承自 Thread,是一个新创建的线程,在构造时自动启动:
public Timer(String name) { | |
thread.setName(name); | |
thread.start(); | |
} |
而它的 run 方法会循环地读取队列中是否还有任务,如果有任务依次执行,没有的话就暂时处于休眠状态:
public void run() { | |
try { | |
mainLoop(); | |
} finally { | |
// Someone killed this Thread, behave as if Timer cancelled | |
synchronized(queue) { | |
newTasksMayBeScheduled = false; | |
queue.clear(); // Eliminate obsolete references | |
} | |
} | |
} | |
/** | |
* The main timer loop. (See class comment.) | |
*/ | |
private void mainLoop() { | |
try { | |
TimerTask task; | |
boolean taskFired; | |
synchronized(queue) { | |
// Wait for queue to become non-empty | |
while (queue.isEmpty() && newTasksMayBeScheduled) // 当队列为空同时没有被关闭时,会调用 wait () 方法暂时处于等待状态,当有新的任务时,会被唤醒。 | |
queue.wait(); | |
if (queue.isEmpty()) | |
break; // 当被唤醒后都没有任务时,就会结束循环,也就是结束工作线程 | |
... | |
} |
newTasksMayBeScheduled
实际上就是标记当前定时器是否关闭,当它为 false 时,表示已经不会再有新的任务到来,也就是关闭,我们可以通过调用 cancel()
方法来关闭它的工作线程:
public void cancel() { | |
synchronized(queue) { | |
thread.newTasksMayBeScheduled = false; | |
queue.clear(); | |
queue.notify(); // 唤醒 wait 使得工作线程结束 | |
} | |
} |
因此,我们可以在使用完成后,调用 Timer 的 cancel()
方法以正常退出我们的程序:
public static void main(String[] args) { | |
Timer timer = new Timer(); | |
timer.schedule(new TimerTask() { | |
@Override | |
public void run() { | |
System.out.println(Thread.currentThread().getName()); | |
timer.cancel(); // 结束 | |
} | |
}, 1000); | |
} |
# 守护线程
不要把操作系统重的守护进程和守护线程相提并论!
守护进程在后台运行运行,不需要和用户交互,本质和普通进程类似。而守护线程就不一样了,当其他所有的非守护线程结束之后,守护线程自动结束,也就是说,Java 中所有的线程都执行完毕后,守护线程自动结束,因此守护线程不适合进行 IO 操作,只适合打打杂:
public static void main(String[] args) throws InterruptedException{ | |
Thread t = new Thread(() -> { | |
while (true){ | |
try { | |
System.out.println("程序正常运行中..."); | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
t.setDaemon(true); // 设置为守护线程(必须在开始之前,中途是不允许转换的) | |
t.start(); | |
for (int i = 0; i < 5; i++) { | |
Thread.sleep(1000); | |
} | |
} |
在守护线程中产生的新线程也是守护的:
public static void main(String[] args) throws InterruptedException{ | |
Thread t = new Thread(() -> { | |
Thread it = new Thread(() -> { | |
while (true){ | |
try { | |
System.out.println("程序正常运行中..."); | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
it.start(); | |
}); | |
t.setDaemon(true); // 设置为守护线程(必须在开始之前,中途是不允许转换的) | |
t.start(); | |
for (int i = 0; i < 5; i++) { | |
Thread.sleep(1000); | |
} | |
} |
# 再谈集合类
集合类中有一个东西是 Java8 新增的 Spliterator 接口,翻译过来就是:可拆分迭代器(Splitable Iterator)和 Iterator 一样,Spliterator 也用于遍历数据源中的元素,但它是为了并行执行而设计的。Java 8 已经为集合框架中包含的所有数据结构提供了一个默认的 Spliterator 实现。在集合跟接口 Collection 中提供了一个 spliterator()
方法用于获取可拆分迭代器。
其实我们之前在讲解集合类的根接口时,就发现有这样一个方法:
default Stream<E> parallelStream() { | |
return StreamSupport.stream(spliterator(), true); //parallelStream 就是利用了可拆分迭代器进行多线程操作 | |
} |
并行流,其实就是一个多线程执行的流,它通过默认的 ForkJoinPool 实现(这里不讲解原理),它可以提高你的多线程任务的速度。
public static void main(String[] args) { | |
List<Integer> list = new ArrayList<>(Arrays.asList(1, 4, 5, 2, 9, 3, 6, 0)); | |
list | |
.parallelStream() // 获得并行流 | |
.forEach(i -> System.out.println(Thread.currentThread().getName()+" -> "+i)); | |
} |
我们发现,forEach 操作的顺序,并不是我们实际 List 中的顺序,同时每次打印也是不同的线程在执行!我们可以通过调用 forEachOrdered()
方法来使用单线程维持原本的顺序:
public static void main(String[] args) { | |
List<Integer> list = new ArrayList<>(Arrays.asList(1, 4, 5, 2, 9, 3, 6, 0)); | |
list | |
.parallelStream() // 获得并行流 | |
.forEachOrdered(System.out::println); | |
} |
我们之前还发现,在 Arrays 数组工具类中,也包含大量的并行方法:
public static void main(String[] args) { | |
int[] arr = new int[]{1, 4, 5, 2, 9, 3, 6, 0}; | |
Arrays.parallelSort(arr); // 使用多线程进行并行排序,效率更高 | |
System.out.println(Arrays.toString(arr)); | |
} |
更多地使用并行方法,可以更加充分地发挥现代计算机多核心的优势,但是同时需要注意多线程产生的异步问题!
public static void main(String[] args) { | |
int[] arr = new int[]{1, 4, 5, 2, 9, 3, 6, 0}; | |
Arrays.parallelSetAll(arr, i -> { | |
System.out.println(Thread.currentThread().getName()); | |
return arr[i]; | |
}); | |
System.out.println(Arrays.toString(arr)); | |
} |
因为多线程的加入,我们之前认识的集合类都废掉了:
public static void main(String[] args) throws InterruptedException { | |
List<Integer> list = new ArrayList<>(); | |
new Thread(() -> { | |
for (int i = 0; i < 1000; i++) { | |
list.add(i); // 两个线程同时操作集合类进行插入操作 | |
} | |
}).start(); | |
new Thread(() -> { | |
for (int i = 1000; i < 2000; i++) { | |
list.add(i); | |
} | |
}).start(); | |
Thread.sleep(2000); | |
System.out.println(list.size()); | |
} |
我们发现,有些时候运气不好,得到的结果并不是 2000 个元素,而是:
因为之前的集合类,并没有考虑到多线程运行的情况,如果两个线程同时执行,那么有可能两个线程同一时间都执行同一个方法,这种情况下就很容易出问题:
public boolean add(E e) { | |
ensureCapacityInternal(size + 1); // 当数组容量更好还差一个满的时候,这个时候两个线程同时走到了这里,因为都判断为没满,所以说没有进行扩容,但是实际上两个线程都要插入一个元素进来 | |
elementData[size++] = e; // 当两个线程同时在这里插入元素,直接导致越界访问 | |
return true; | |
} |
当然,在 Java 早期的时候,还有一些老的集合类,这些集合类都是线程安全的:
public static void main(String[] args) throws InterruptedException { | |
Vector<Integer> list = new Vector<>(); // 我们可以使用 Vector 代替 List 使用 | |
//Hashtable<Integer, String> 也可以使用 Hashtable 来代替 Map | |
new Thread(() -> { | |
for (int i = 0; i < 1000; i++) { | |
list.add(i); | |
} | |
}).start(); | |
new Thread(() -> { | |
for (int i = 1000; i < 2000; i++) { | |
list.add(i); | |
} | |
}).start(); | |
Thread.sleep(1000); | |
System.out.println(list.size()); | |
} |
因为这些集合类中的每一个方法都加了锁,所以说不会出现多线程问题,但是这些老的集合类现在已经不再使用了,我们会在 JUC 篇视频教程中介绍专用于并发编程的集合类。
通过对 Java 多线程的了解,我们就具备了利用多线程解决问题的思维!
# 实战:生产者与消费者
所谓的生产者消费者模型,是通过一个容器来解决生产者和消费者的强耦合问题。通俗的讲,就是生产者在不断的生产,消费者也在不断的消费,可是消费者消费的产品是生产者生产的,这就必然存在一个中间容器,我们可以把这个容器想象成是一个货架,当货架空的时候,生产者要生产产品,此时消费者在等待生产者往货架上生产产品,而当货架有货物的时候,消费者可以从货架上拿走商品,生产者此时等待货架出现空位,进而补货,这样不断的循环。
通过多线程编程,来模拟一个餐厅的 2 个厨师和 3 个顾客,假设厨师炒出一个菜的时间为 3 秒,顾客吃掉菜品的时间为 4 秒。
# 反射
** 注意:** 本章节涉及到 JVM 相关底层原理,难度会有一些大。
反射就是把 Java 类中的各个成分映射成一个个的 Java 对象。即在运行状态中,对于任意一个类,都能够知道这个类所有的属性和方法,对于任意一个对象,都能调用它的任意一个方法和属性。这种动态获取信息及动态调用对象方法的功能叫 Java 的反射机制。
简而言之,我们可以通过反射机制,获取到类的一些属性,包括类里面有哪些字段,有哪些方法,继承自哪个类,甚至还能获取到泛型!它的权限非常高,慎重使用!
# Java 类加载机制
在学习 Java 的反射机制之前,我们需要先了解一下类的加载机制,一个类是如何被加载和使用的:
在 Java 程序启动时,JVM 会将一部分类(class 文件)先加载(并不是所有的类都会在一开始加载),通过 ClassLoader 将类加载,在加载过程中,会将类的信息提取出来(存放在元空间中,JDK1.8 之前存放在永久代),同时也会生成一个 Class 对象存放在内存(堆内存),注意此 Class 对象只会存在一个,与加载的类唯一对应!
为了方便各位小伙伴理解,你们就直接理解为默认情况下(仅使用默认类加载器)每个类都有且只有一个唯一的 Class 对象存放在 JVM 中,我们无论通过什么方式访问,都是始终是那一个对象。Class 对象中包含我们类的一些信息,包括类里面有哪些方法、哪些变量等等。
# Class 类详解
通过前面,我们了解了类的加载,同时会提取一个类的信息生成 Class 对象存放在内存中,而反射机制其实就是利用这些存放的类信息,来获取类的信息和操作类。那么如何获取到每个类对应的 Class 对象呢,我们可以通过以下方式:
public static void main(String[] args) throws ClassNotFoundException { | |
Class<String> clazz = String.class; // 使用 class 关键字,通过类名获取 | |
Class<?> clazz2 = Class.forName("java.lang.String"); // 使用 Class 类静态方法 forName (),通过包名。类名获取,注意返回值是 Class<?> | |
Class<?> clazz3 = new String("cpdd").getClass(); // 通过实例对象获取 | |
} |
注意 Class 类也是一个泛型类,只有第一种方法,能够直接获取到对应类型的 Class 对象,而以下两种方法使用了 ?
通配符作为返回值,但是实际上都和第一个返回的是同一个对象:
Class<String> clazz = String.class; // 使用 class 关键字,通过类名获取 | |
Class<?> clazz2 = Class.forName("java.lang.String"); // 使用 Class 类静态方法 forName (),通过包名。类名获取,注意返回值是 Class<?> | |
Class<?> clazz3 = new String("cpdd").getClass(); | |
System.out.println(clazz == clazz2); | |
System.out.println(clazz == clazz3); |
通过比较,验证了我们一开始的结论,在 JVM 中每个类始终只存在一个 Class 对象,无论通过什么方法获取,都是一样的。现在我们再来看看这个问题:
public static void main(String[] args) { | |
Class<?> clazz = int.class; // 基本数据类型有 Class 对象吗? | |
System.out.println(clazz); | |
} |
迷了,不是每个类才有 Class 对象吗,基本数据类型又不是类,这也行吗?实际上,基本数据类型也有对应的 Class 对象(反射操作可能需要用到),而且我们不仅可以通过 class 关键字获取,其实本质上是定义在对应的包装类中的:
/** | |
* The {@code Class} instance representing the primitive type | |
* {@code int}. | |
* | |
* @since JDK1.1 | |
*/ | |
@SuppressWarnings("unchecked") | |
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int"); | |
/* | |
* Return the Virtual Machine's Class object for the named | |
* primitive type | |
*/ | |
static native Class<?> getPrimitiveClass(String name); //C++ 实现,并非 Java 定义 |
每个包装类中(包括 Void),都有一个获取原始类型 Class 方法,注意,getPrimitiveClass 获取的是原始类型,并不是包装类型,只是可以使用包装类来表示。
public static void main(String[] args) { | |
Class<?> clazz = int.class; | |
System.out.println(Integer.TYPE == int.class); | |
} |
通过对比,我们发现实际上包装类型都有一个 TYPE,其实也就是基本类型的 Class,那么包装类的 Class 和基本类的 Class 一样吗?
public static void main(String[] args) { | |
System.out.println(Integer.TYPE == Integer.class); | |
} |
我们发现,包装类型的 Class 对象并不是基本类型 Class 对象。数组类型也是一种类型,只是编程不可见,因此我们可以直接获取数组的 Class 对象:
public static void main(String[] args) { | |
Class<String[]> clazz = String[].class; | |
System.out.println(clazz.getName()); // 获取类名称(得到的是包名 + 类名的完整名称) | |
System.out.println(clazz.getSimpleName()); | |
System.out.println(clazz.getTypeName()); | |
System.out.println(clazz.getClassLoader()); // 获取它的类加载器 | |
System.out.println(clazz.cast(new Integer("10"))); // 强制类型转换 | |
} |
下节课,我们将开始对 Class 对象的使用进行讲解。
# Class 对象与多态
正常情况下,我们使用 instanceof 进行类型比较:
public static void main(String[] args) { | |
String str = ""; | |
System.out.println(str instanceof String); | |
} |
它可以判断一个对象是否为此接口或是类的实现或是子类,而现在我们有了更多的方式去判断类型:
public static void main(String[] args) { | |
String str = ""; | |
System.out.println(str.getClass() == String.class); // 直接判断是否为这个类型 | |
} |
如果需要判断是否为子类或是接口 / 抽象类的实现,我们可以使用 asSubClass()
方法:
public static void main(String[] args) { | |
Integer i = 10; | |
i.getClass().asSubclass(Number.class); // 当 Integer 不是 Number 的子类时,会产生异常 | |
} |
通过 getSuperclass()
方法,我们可以获取到父类的 Class 对象:
public static void main(String[] args) { | |
Integer i = 10; | |
System.out.println(i.getClass().getSuperclass()); | |
} |
也可以通过 getGenericSuperclass()
获取父类的原始类型的 Type:
public static void main(String[] args) { | |
Integer i = 10; | |
Type type = i.getClass().getGenericSuperclass(); | |
System.out.println(type); | |
System.out.println(type instanceof Class); | |
} |
我们发现 Type 实际上是 Class 类的父接口,但是获取到的 Type 的实现并不一定是 Class。
同理,我们也可以像上面这样获取父接口:
public static void main(String[] args) { | |
Integer i = 10; | |
for (Class<?> anInterface : i.getClass().getInterfaces()) { | |
System.out.println(anInterface.getName()); | |
} | |
for (Type genericInterface : i.getClass().getGenericInterfaces()) { | |
System.out.println(genericInterface.getTypeName()); | |
} | |
} |
是不是感觉反射功能很强大?几乎类的所有信息都可以通过反射获得。
# 创建类对象
既然我们拿到了类的定义,那么是否可以通过 Class 对象来创建对象、调用方法、修改变量呢?当然是可以的,那我们首先来探讨一下如何创建一个类的对象:
public static void main(String[] args) throws InstantiationException, IllegalAccessException { | |
Class<Student> clazz = Student.class; | |
Student student = clazz.newInstance(); | |
student.test(); | |
} | |
static class Student{ | |
public void test(){ | |
System.out.println("萨日朗"); | |
} | |
} |
通过使用 newInstance()
方法来创建对应类型的实例,返回泛型 T,注意它会抛出 InstantiationException 和 IllegalAccessException 异常,那么什么情况下会出现异常呢?
public static void main(String[] args) throws InstantiationException, IllegalAccessException { | |
Class<Student> clazz = Student.class; | |
Student student = clazz.newInstance(); | |
student.test(); | |
} | |
static class Student{ | |
public Student(String text){ | |
} | |
public void test(){ | |
System.out.println("萨日朗"); | |
} | |
} |
当类默认的构造方法被带参构造覆盖时,会出现 InstantiationException 异常,因为 newInstance()
只适用于默认无参构造。
public static void main(String[] args) throws InstantiationException, IllegalAccessException { | |
Class<Student> clazz = Student.class; | |
Student student = clazz.newInstance(); | |
student.test(); | |
} | |
static class Student{ | |
private Student(){} | |
public void test(){ | |
System.out.println("萨日朗"); | |
} | |
} |
当默认无参构造的权限不是 public
时,会出现 IllegalAccessException 异常,表示我们无权去调用默认构造方法。在 JDK9 之后,不再推荐使用 newInstance()
方法了,而是使用我们接下来要介绍到的,通过获取构造器,来实例化对象:
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { | |
Class<Student> clazz = Student.class; | |
Student student = clazz.getConstructor(String.class).newInstance("what's up"); | |
student.test(); | |
} | |
static class Student{ | |
public Student(String str){} | |
public void test(){ | |
System.out.println("萨日朗"); | |
} | |
} |
通过获取类的构造方法(构造器)来创建对象实例,会更加合理,我们可以使用 getConstructor()
方法来获取类的构造方法,同时我们需要向其中填入参数,也就是构造方法需要的类型,当然我们这里只演示了。那么,当访问权限不是 public 的时候呢?
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { | |
Class<Student> clazz = Student.class; | |
Student student = clazz.getConstructor(String.class).newInstance("what's up"); | |
student.test(); | |
} | |
static class Student{ | |
private Student(String str){} | |
public void test(){ | |
System.out.println("萨日朗"); | |
} | |
} |
我们发现,当访问权限不足时,会无法找到此构造方法,那么如何找到非 public 的构造方法呢?
Class<Student> clazz = Student.class; | |
Constructor<Student> constructor = clazz.getDeclaredConstructor(String.class); | |
constructor.setAccessible(true); // 修改访问权限 | |
Student student = constructor.newInstance("what's up"); | |
student.test(); |
使用 getDeclaredConstructor()
方法可以找到类中的非 public 构造方法,但是在使用之前,我们需要先修改访问权限,在修改访问权限之后,就可以使用非 public 方法了(这意味着,反射可以无视权限修饰符访问类的内容)
# 调用类方法
我们可以通过反射来调用类的方法(本质上还是类的实例进行调用)只是利用反射机制实现了方法的调用,我们在包下创建一个新的类:
package com.test; | |
public class Student { | |
public void test(String str){ | |
System.out.println("萨日朗"+str); | |
} | |
} |
这次我们通过 forName(String)
来找到这个类并创建一个新的对象:
public static void main(String[] args) throws ReflectiveOperationException { | |
Class<?> clazz = Class.forName("com.test.Student"); | |
Object instance = clazz.newInstance(); // 创建出学生对象 | |
Method method = clazz.getMethod("test", String.class); // 通过方法名和形参类型获取类中的方法 | |
method.invoke(instance, "what's up"); // 通过 Method 对象的 invoke 方法来调用方法 | |
} |
通过调用 getMethod()
方法,我们可以获取到类中所有声明为 public 的方法,得到一个 Method 对象,我们可以通过 Method 对象的 invoke()
方法(返回值就是方法的返回值,因为这里是 void,返回值为 null)来调用已经获取到的方法,注意传参。
我们发现,利用反射之后,在一个对象从构造到方法调用,没有任何一处需要引用到对象的实际类型,我们也没有导入 Student 类,整个过程都是反射在代替进行操作,使得整个过程被模糊了,过多的使用反射,会极大地降低后期维护性。
同构造方法一样,当出现非 public 方法时,我们可以通过反射来无视权限修饰符,获取非 public 方法并调用,现在我们将 test()
方法的权限修饰符改为 private:
public static void main(String[] args) throws ReflectiveOperationException { | |
Class<?> clazz = Class.forName("com.test.Student"); | |
Object instance = clazz.newInstance(); // 创建出学生对象 | |
Method method = clazz.getDeclaredMethod("test", String.class); // 通过方法名和形参类型获取类中的方法 | |
method.setAccessible(true); | |
method.invoke(instance, "what's up"); // 通过 Method 对象的 invoke 方法来调用方法 | |
} |
Method 和 Constructor 都和 Class 一样,他们存储了方法的信息,包括方法的形式参数列表,返回值,方法的名称等内容,我们可以直接通过 Method 对象来获取这些信息:
public static void main(String[] args) throws ReflectiveOperationException { | |
Class<?> clazz = Class.forName("com.test.Student"); | |
Method method = clazz.getDeclaredMethod("test", String.class); // 通过方法名和形参类型获取类中的方法 | |
System.out.println(method.getName()); // 获取方法名称 | |
System.out.println(method.getReturnType()); // 获取返回值类型 | |
} |
当方法的参数为可变参数时,我们该如何获取方法呢?实际上,我们在之前就已经提到过,可变参数实际上就是一个数组,因此我们可以直接使用数组的 class 对象表示:
Method method = clazz.getDeclaredMethod("test", String[].class); |
反射非常强大,尤其是我们提到的越权访问,但是请一定谨慎使用,别人将某个方法设置为 private 一定有他的理由,如果实在是需要使用别人定义为 private 的方法,就必须确保这样做是安全的,在没有了解别人代码的整个过程就强行越权访问,可能会出现无法预知的错误。
# 修改类的属性
我们还可以通过反射访问一个类中定义的成员字段也可以修改一个类的对象中的成员字段值,通过 getField()
方法来获取一个类定义的指定字段:
public static void main(String[] args) throws ReflectiveOperationException { | |
Class<?> clazz = Class.forName("com.test.Student"); | |
Object instance = clazz.newInstance(); | |
Field field = clazz.getField("i"); // 获取类的成员字段 i | |
field.set(instance, 100); // 将类实例 instance 的成员字段 i 设置为 100 | |
Method method = clazz.getMethod("test"); | |
method.invoke(instance); | |
} |
在得到 Field 之后,我们就可以直接通过 set()
方法为某个对象,设定此属性的值,比如上面,我们就为 instance 对象设定值为 100,当访问 private 字段时,同样可以按照上面的操作进行越权访问:
public static void main(String[] args) throws ReflectiveOperationException { | |
Class<?> clazz = Class.forName("com.test.Student"); | |
Object instance = clazz.newInstance(); | |
Field field = clazz.getDeclaredField("i"); // 获取类的成员字段 i | |
field.setAccessible(true); | |
field.set(instance, 100); // 将类实例 instance 的成员字段 i 设置为 100 | |
Method method = clazz.getMethod("test"); | |
method.invoke(instance); | |
} |
现在我们已经知道,反射几乎可以把一个类的老底都给扒出来,任何属性,任何内容,都可以被反射修改,无论权限修饰符是什么,那么,如果我的字段被标记为 final 呢?现在在字段 i
前面添加 final
关键字,我们再来看看效果:
private final int i = 10; |
这时,当字段为 final 时,就修改失败了!当然,通过反射可以直接将 final 修饰符直接去除,去除后,就可以随意修改内容了,我们来尝试修改 Integer 的 value 值:
public static void main(String[] args) throws ReflectiveOperationException { | |
Integer i = 10; | |
Field field = Integer.class.getDeclaredField("value"); | |
Field modifiersField = Field.class.getDeclaredField("modifiers"); // 这里要获取 Field 类的 modifiers 字段进行修改 | |
modifiersField.setAccessible(true); | |
modifiersField.setInt(field,field.getModifiers()&~Modifier.FINAL); // 去除 final 标记 | |
field.setAccessible(true); | |
field.set(i, 100); // 强行设置值 | |
System.out.println(i); | |
} |
我们可以发现,反射非常暴力,就连被定义为 final 字段的值都能强行修改,几乎能够无视一切阻拦。我们来试试看修改一些其他的类型:
public static void main(String[] args) throws ReflectiveOperationException { | |
List<String> i = new ArrayList<>(); | |
Field field = ArrayList.class.getDeclaredField("size"); | |
field.setAccessible(true); | |
field.set(i, 10); | |
i.add("测试"); // 只添加一个元素 | |
System.out.println(i.size()); // 大小直接变成 11 | |
i.remove(10); // 瞎移除都不带报错的,淦 | |
} |
实际上,整个 ArrayList 体系由于我们的反射操作,导致被破坏,因此它已经无法正常工作了!
再次强调,在进行反射操作时,必须注意是否安全,虽然拥有了创世主的能力,但是我们不能滥用,我们只能把它当做一个不得已才去使用的工具!
# 类加载器
我们接着来介绍一下类加载器,实际上类加载器就是用于加载一个类的,但是类加载器并不是只有一个。
** 思考:** 既然说 Class 对象和加载的类唯一对应,那如果我们手动创建一个与 JDK 包名一样,同时类名也保持一致,JVM 会加载这个类吗?
package java.lang; | |
public class String { //JDK 提供的 String 类也是 | |
public static void main(String[] args) { | |
System.out.println("我姓🐴,我叫🐴nb"); | |
} | |
} |
我们发现,会出现以下报错:
错误: 在类 java.lang.String 中找不到 main 方法, 请将 main 方法定义为: | |
public static void main(String[] args) |
但是我们明明在自己写的 String 类中定义了 main 方法啊,为什么会找不到此方法呢?实际上这是 ClassLoader 的 双亲委派机制
在保护 Java 程序的正常运行:
实际上类最开始是由 BootstarpClassLoader 进行加载,BootstarpClassLoader 用于加载 JDK 提供的类,而我们自己编写的类实际上是 AppClassLoader 加载的,只有 BootstarpClassLoader 都没有加载的类,才会让 AppClassLoader 来加载,因此我们自己编写的同名包同名类不会被加载,而实际要去启动的是真正的 String 类,也就自然找不到 main
方法了。
public class Main { | |
public static void main(String[] args) { | |
System.out.println(Main.class.getClassLoader()); // 查看当前类的类加载器 | |
System.out.println(Main.class.getClassLoader().getParent()); // 父加载器 | |
System.out.println(Main.class.getClassLoader().getParent().getParent()); // 爷爷加载器 | |
System.out.println(String.class.getClassLoader()); //String 类的加载器 | |
} | |
} |
由于 BootstarpClassLoader 是 C++ 编写的,我们在 Java 中是获取不到的。
既然通过 ClassLoader 就可以加载类,那么我们可以自己手动将 class 文件加载到 JVM 中吗?先写好我们定义的类:
package com.test; | |
public class Test { | |
public String text; | |
public void test(String str){ | |
System.out.println(text+" > 我是测试方法!"+str); | |
} | |
} |
通过 javac 命令,手动编译一个.class 文件:
nagocoler@NagodeMacBook-Pro HelloWorld % javac src/main/java/com/test/Test.java |
编译后,得到一个 class 文件,我们把它放到根目录下,然后编写一个我们自己的 ClassLoader,因为普通的 ClassLoader 无法加载二进制文件,因此我们编写一个自定义的来让它支持:
// 定义一个自己的 ClassLoader | |
static class MyClassLoader extends ClassLoader{ | |
public Class<?> defineClass(String name, byte[] b){ | |
return defineClass(name, b, 0, b.length); // 调用 protected 方法,支持载入外部 class 文件 | |
} | |
} | |
public static void main(String[] args) throws IOException { | |
MyClassLoader classLoader = new MyClassLoader(); | |
FileInputStream stream = new FileInputStream("Test.class"); | |
byte[] bytes = new byte[stream.available()]; | |
stream.read(bytes); | |
Class<?> clazz = classLoader.defineClass("com.test.Test", bytes); // 类名必须和我们定义的保持一致 | |
System.out.println(clazz.getName()); // 成功加载外部 class 文件 | |
} |
现在,我们就将此 class 文件读取并解析为 Class 了,现在我们就可以对此类进行操作了(注意,我们无法在代码中直接使用此类型,因为它是我们直接加载的),我们来试试看创建一个此类的对象并调用其方法:
try { | |
Object obj = clazz.newInstance(); | |
Method method = clazz.getMethod("test", String.class); // 获取我们定义的 test (String str) 方法 | |
method.invoke(obj, "哥们这瓜多少钱一斤?"); | |
}catch (Exception e){ | |
e.printStackTrace(); | |
} |
我们来试试看修改成员字段之后,再来调用此方法:
try { | |
Object obj = clazz.newInstance(); | |
Field field = clazz.getField("text"); // 获取成员变量 String text; | |
field.set(obj, "华强"); | |
Method method = clazz.getMethod("test", String.class); // 获取我们定义的 test (String str) 方法 | |
method.invoke(obj, "哥们这瓜多少钱一斤?"); | |
}catch (Exception e){ | |
e.printStackTrace(); | |
} |
通过这种方式,我们就可以实现外部加载甚至是网络加载一个类,只需要把类文件传递即可,这样就无需再将代码写在本地,而是动态进行传递,不仅可以一定程度上防止源代码被反编译(只是一定程度上,想破解你代码有的是方法),而且在更多情况下,我们还可以对 byte [] 进行加密,保证在传输过程中的安全性。
# 注解
** 注意:** 注解跟我们之前讲解的注释完全不是一个概念,不要搞混了。
其实我们在之前就接触到注解了,比如 @Override
表示重写父类方法(当然不加效果也是一样的,此注解在编译时会被自动丢弃)注解本质上也是一个类,只不过它的用法比较特殊。
注解可以被标注在任意地方,包括方法上、类名上、参数上、成员属性上、注解定义上等,就像注释一样,它相当于我们对某样东西的一个标记。而与注释不同的是,注解可以通过反射在运行时获取,注解也可以选择是否保留到运行时。
# 预设注解
JDK 预设了以下注解,作用于代码:
- @Override - 检查(仅仅是检查,不保留到运行时)该方法是否是重写方法。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。
- @Deprecated - 标记过时方法。如果使用该方法,会报编译警告。
- @SuppressWarnings - 指示编译器去忽略注解中声明的警告(仅仅编译器阶段,不保留到运行时)
- @FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。
- @SafeVarargs - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
# 元注解
元注解是作用于注解上的注解,用于我们编写自定义的注解:
- @Retention - 标识这个注解怎么保存,是只在代码中,还是编入 class 文件中,或者是在运行时可以通过反射访问。
- @Documented - 标记这些注解是否包含在用户文档中。
- @Target - 标记这个注解应该是哪种 Java 成员。
- @Inherited - 标记这个注解是继承于哪个注解类 (默认 注解并没有继承于任何子类)
- @Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。
看了这么多预设的注解,你们肯定眼花缭乱了,那我们来看看 @Override
是如何定义的:
@Target(ElementType.METHOD) | |
@Retention(RetentionPolicy.SOURCE) | |
public @interface Override { | |
} |
该注解由 @Target
限定为只能作用于方法上,ElementType 是一个枚举类型,用于表示此枚举的作用域,一个注解可以有很多个作用域。 @Retention
表示此注解的保留策略,包括三种策略,在上述中有写到,而这里定义为只在代码中。一般情况下,自定义的注解需要定义 1 个 @Retention
和 1-n 个 @Target
。
既然了解了元注解的使用和注解的定义方式,我们就来尝试定义一个自己的注解:
@Target(ElementType.METHOD) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Test { | |
} |
这里我们定义一个 Test 注解,并将其保留到运行时,同时此注解可以作用于方法或是类上:
@Test | |
public class Main { | |
@Test | |
public static void main(String[] args) { | |
} | |
} |
这样,一个最简单的注解就被我们创建了。
# 注解的使用
我们还可以在注解中定义一些属性,注解的属性也叫做成员变量,注解只有成员变量,没有方法。注解的成员变量在注解的定义中以 “无形参的方法” 形式来声明,其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型:
@Target({ElementType.METHOD, ElementType.TYPE}) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Test { | |
String value(); | |
} |
默认只有一个属性时,我们可以将其名字设定为 value,否则,我们需要在使用时手动指定注解的属性名称,使用 value 则无需填入:
@Target({ElementType.METHOD, ElementType.TYPE}) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Test { | |
String test(); | |
} |
public class Main { | |
@Test(test = "") | |
public static void main(String[] args) { | |
} | |
} |
我们也可以使用 default 关键字来为这些属性指定默认值:
@Target({ElementType.METHOD, ElementType.TYPE}) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Test { | |
String value() default "都看到这里了,给个三连吧!"; | |
} |
当属性存在默认值时,使用注解的时候可以不用传入属性值。当属性为数组时呢?
@Target({ElementType.METHOD, ElementType.TYPE}) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Test { | |
String[] value(); | |
} |
当属性为数组,我们在使用注解传参时,如果数组里面只有一个内容,我们可以直接传入一个值,而不是创建一个数组:
@Test("关注点了吗") | |
public static void main(String[] args) { | |
} |
public class Main { | |
@Test({"value1", "value2"}) // 多个值时就使用花括号括起来 | |
public static void main(String[] args) { | |
} | |
} |
# 反射获取注解
既然我们的注解可以保留到运行时,那么我们来看看,如何获取我们编写的注解,我们需要用到反射机制:
public static void main(String[] args) { | |
Class<Student> clazz = Student.class; | |
for (Annotation annotation : clazz.getAnnotations()) { | |
System.out.println(annotation.annotationType()); // 获取类型 | |
System.out.println(annotation instanceof Test); // 直接判断是否为 Test | |
Test test = (Test) annotation; | |
System.out.println(test.value()); // 获取我们在注解中写入的内容 | |
} | |
} |
通过反射机制,我们可以快速获取到我们标记的注解,同时还能获取到注解中填入的值,那么我们来看看,方法上的标记是不是也可以通过这种方式获取注解:
public static void main(String[] args) throws NoSuchMethodException { | |
Class<Student> clazz = Student.class; | |
for (Annotation annotation : clazz.getMethod("test").getAnnotations()) { | |
System.out.println(annotation.annotationType()); // 获取类型 | |
System.out.println(annotation instanceof Test); // 直接判断是否为 Test | |
Test test = (Test) annotation; | |
System.out.println(test.value()); // 获取我们在注解中写入的内容 | |
} | |
} |
无论是方法、类、还是字段,都可以使用 getAnnotations()
方法(还有几个同名的)来快速获取我们标记的注解。
所以说呢,这玩意学来有啥用?丝毫 get 不到这玩意的用处。其实不是,现阶段作为初学者,还体会不到注解带来的快乐,在接触到 Spring 和 SpringBoot 等大型框架后,相信各位就能感受到注解带来的魅力了。
# 结束语
Java 的学习对你来说可能是枯燥的,可能是漫长的,也有可能是有趣的,无论如何,你终于是完成了全部内容的学习,可喜可贺。
实际上很多人一开始跟着你们一起在进行学习,但是他们因为各种原因,最后还是没有走完这条路。坚持不一定会成功,但坚持到别人坚持不下去,那么你至少已经成功了一半了,坚持到最后的人运气往往都不会太差。
希望各位小伙伴能够在之后的学习中砥砺前行!