目录
什么是线程不安全,请看以下代码:
- public class ThreadDemo1 {
- static int N = 10_0000;
- static int res = 0;
-
- public static class MyRunnable implements Runnable {
- @Override
- public void run() {
- for (int i = 0; i < N; i ++) {
- res++;
- }
- }
- }
-
- public static void main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new MyRunnable());
- t1.start();
- for (int i = 0; i < N; i ++) {
- res--;
- }
- t1.join();
- System.out.println(res);
- }
- }
我们进行了等量的操作(对res ++ 和 res -- ) 观察结果:

为什么不是0 而是一个奇怪的数字,当我们再次执行观察:

这就是线程不安全导致的。
通俗的讲:如果在多线程环境下代码运行的结果是符合我们预期的,即在单线程环境应该的结果,则说明这个程序是线程安全的
修改共享数据
上面的线程不安全的代码中,涉及到多个线程对 res 变量进行修改

由于这个变量在方法区上,因此多个线程都能进行访问和修改,
我们直到计算机根据指令工作,思考以下情景:
我们对res++ 在从寄存器中拿出 res ,++完成之后准备放回,而此时恰好发生了线程调度,又拿出res -- 完成之后 我们的++操作被调度回来 我们放回 ,但此时++的操作已经被 -- 覆盖了。
什么是原子性
我们把代码想象成一个房间,每个线程就是要进入这个房间的人,如果没有任何机制,A进入房间以后还没出来,B此时也进入房间,打断了A的隐私,这个就没有具备原子性
因此我们需要一把锁,当A进入房间后,加上锁后其他人不允许进入房间,这样就保证了代码的原子性,有时我们也把它叫做同步互斥
可见性
可见性是指,一个线程对共享数据的修改,能够及时被其他线程看到
java内存模型(JMM):java虚拟机中规范定义了java内存模型。
目的是屏蔽掉各种硬件和操作系统的内存访问差异,以实现让java程序在各种平台下能达到一致的并发性。

因为每个线程有自己独立的工作内存,因此修改其中一个工作内存的值 ,另一个工作内存不一定及时变化。
代码顺序性
什么是代码重排序?
假设一段代码:
1、去前台取U盘
2、去教室写10分钟作业
3、去前台取快递
如果是在单线程环境下:JVM,CPU会对其优化 1->3->2 可以少跑一次前台
什么情况下数据会存在安全问题呢?
得满足以下三个条件
1、多线程并发
2、有共享数据
3、有修改行为
怎么解决线程不安全的问题?
- public class ThreadDemo1 {
- static int N = 10_0000;
- static int res = 0;
- static Object sys = new Object();
-
- public static class MyRunnable implements Runnable {
- @Override
- public void run() {
- synchronized (sys) {
- for (int i = 0; i < N; i ++) {
- res++;
- }
- }
-
- }
- }
-
- public static void main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new MyRunnable());
- t1.start();
- synchronized (sys) {
- for (int i = 0; i < N; i ++) {
- res--;
- }
- }
- t1.join();
- System.out.println(res);
- }
- }
我们对于res++ 和 res--的操作都加上了sys这把锁,因此我们可以得到准确的结果

互斥
synchronized 会起到互斥效果 ,某个线程执行到某个对象的synchronized 中时,其他线程如果也执行到同一个对象synchronized 就会阻塞等待

可以粗略的理解成:每个对象在内存中存储的时候,都存有一块区域表示当前的“锁定”状态,如果当前是“无人”状态,那么就可以使用,使用时都需要设为“有人”状态。
当前是“有人”状态,那就只能排队


刷新内存
synchronized 的工作过程:
1、获得互斥锁
2、从主内存中拷贝变量的最新副本到工作内存
3、执行代码
4、将更改后的共享变量的值刷新到主内存
5、释放互斥锁
可重入
synchronized 同步块对同一条线程来说是可重入的,不会出现把自己锁死的问题。




java标准库中很多线程都是不安全的,这些类可能会涉及到多线程修改共享数据,但又没有加锁措施

一些线程安全的类:



代码在写入volatile 修饰的变量的时候:
改变线程工作内存中变量的值
将改变后的值从工作内存刷新到主内存
代码在读取volatile 修饰的变量的时候:
从主内存中读取最新值到工作内存
从工作内存中读取volatile变量的副本

- public class ThreadDemo1 {
- static class Counter {
- int flag = 0;
- }
-
- public static void main(String[] args) {
- Counter c = new Counter();
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- while (c.flag == 0) {
-
- }
- System.out.println("循环结束!");
- }
- });
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run() {
- System.out.println("输入一个整数以改变flag的值");
- Scanner sc = new Scanner(System.in);
- c.flag = sc.nextInt();
- }
- });
- t1.start();
- t2.start();
-
- }
- }
我们本设想 t2 改变了 flag 的值 t1 应该停止循环,但由于 t1 读的是自己工作内存中的内容,因此即使 t2 对 flag 变量修改,t1 感知不到 flag 的变化
因此我们要给 flag 加上volatile


2、volatile 不保证原子性
volatile 和 synchronized 有着本质的区别,synchronized 能够保证原子性, valatile 保证的是内存可见性
- public class ThreadDemo1 {
- static volatile int res = 0;
- Object o = new Object();
-
- public static void main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- for (int i = 0; i < 10000000; i ++) res++;
- }
- });
- t1.start();
- for (int i = 0; i < 10000000; i ++) res--;
- t1.join();
- System.out.println(res);
- }
- }

即使我们加上volatile 但结果仍然不是0
因为我们 volatile 保证的是如果其他线程更改res ,我们拿到的res是最新的
但不能保证 res++ 的原子性 ,因此依然存在线程不安全
3、synchronized 也能保证内存可见性


由于线程间是抢占执行的,因此线程之间的执行先后顺序难以预知
但是实际开发中有时候我们希望合理协调多个线程之间的执行先后顺序

wait 做的事情:
使当前执行的代码的线程进行等待(把线程放到等待队列中)
释放当前的锁
满足一定条件时唤醒,重新尝试获取这个锁
wait 要搭配 sychronized 来使用,脱离synchronized 使用 wait 会直接抛出异常
wait 结束等待的条件:
其他线程调用该对象的 notify 方法
wait 等待时间超时 (wait 方法提供一个带有 timeout 参数的版本,来指定等待时间)
其他线程调用该线程的 interrupted 方法,导致 wait 抛出 InterruptedException 异常

notify 方法是唤醒等待的线程

接下来我们做一个线程唤醒地小栗子:
- public class ThreadDemo1 {
- static class WaitTask implements Runnable {
- public Object lock;
- public WaitTask(Object lock) {
- this.lock = lock;
- }
- @Override
- public void run() {
- synchronized (lock) {
- while (true) {
- try {
- System.out.println("wait开始");
- lock.wait();
- System.out.println("wait结束");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
-
- static class NotifyTask implements Runnable {
- public Object lock;
- public NotifyTask (Object lock) {
- this.lock = lock;
- }
-
- @Override
- public void run() {
- synchronized (lock) {
- System.out.println("notify开始");
- lock.notify();
- System.out.println("notify结束");
- }
- }
- }
-
- public static void main(String[] args) throws InterruptedException {
- Object lock = new Object();
- Thread t1 = new Thread(new WaitTask(lock));
- Thread t2 = new Thread(new NotifyTask(lock));
- t1.start();
- Thread.sleep(1000);
- t2.start();
- }
- }
首先wait线程执行到wait时释放锁并且等待唤醒,而notify在执行完代码块中所有内容后才会释放锁去唤醒waittask

notifyall方法相比 notify 的不同就是它可以唤醒锁上的所有线程,但线程执行依然有先后顺序,当一个线程占有锁后,其他线程是无法进入的
wait() 和 sleep() 对比?(面试题常考)
首先这两个方法似乎八竿子打不着北,wait()是实现进程间通信的方法,sleep()是让线程阻塞的,唯一的相同点是都能让线程阻塞一段时间
总结:
1、wait()是针对对象(锁)而言的,一定一定需要搭配synchronized使用,sleep不需要
2、wait是Object下的方法,而sleep是Thread下的静态方法
单例模式是最经典的设计模式之一
什么是设计模式?

单例模式就是保证一个类在程序中只存在一份实例,而不会创建多个实例
比如 JDBC 中的 DataSource 实例就只需要一个
单例模式的具体实现可以分为 “饿汉” 和 “懒汉”
类加载的同时,创建实例
- public class ThreadDemo1 {
- public static void main(String[] args) {
- Singleton s = Singleton.getInstance();
- }
- }
-
- class Singleton {
- private static Singleton instance = new Singleton();
- private Singleton() {}
- public static Singleton getInstance() {
- return instance;
- }
- }
这样如果我们要获得SIngleton的实例只能通过getInstance方法,因为无论构造方法还是属性都是private的,
首次调用getInstance时才创建对象(延时加载)
- class Singleton {
- private static Singleton instance = null;
- private Singleton() {}
- public static Singleton getInstance() {
- if (instance == null) instance = new Singleton();
- return instance;
- }
- }
上面的懒汉模式实现其实是不安全的

因此我们加锁改善线程安全问题
使用双重 if 判定,降低锁竞争的频率。
给 instance 加上了 volatile
- class Singleton {
- private volatile static Singleton instance = null;
- private Singleton() {}
- public static Singleton getInstance() {
- if (instance == null) {
- synchronized (Singleton.class) {
- if (instance == null) {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
- }
如何理解 双重if / volatile
加锁/解锁 本身是一件开销比较高的事情,懒汉模式的线程不安全只是发生在首次创建实例的时候,因此后序没必要加锁
外层的if就是判断是不是 instance 实例已经创建出来了
volatile 是为了避免“内存可见性”导致读取的 instance 出现偏差

阻塞队列是一种特殊的队列,遵守“先进先出”的原则
阻塞队列能是一种线程安全的数据结构,并且具有以下特性:
当队列满的时候,继续入队列就会阻塞,直到有其他线程从队列中取走元素
当队列空的时候,继续出队列也会阻塞,直到有其他线程往队列中插入元素
阻塞队列的一个典型应用就是:生产者消费者模型。
生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题
生产者和消费者彼此之间不直接通讯,而是通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列中取


- public static void main(String[] args) throws InterruptedException {
- BlockingDeque<String> queue = new LinkedBlockingDeque<>();
- queue.push("hello");
- String res = queue.take();
- System.out.println(res);
- }
生产者消费者模型:
- public static void main(String[] args) throws InterruptedException {
- BlockingDeque<Integer> queue = new LinkedBlockingDeque<>();
- Thread customer = new Thread(new Runnable() {
- @Override
- public void run() {
- while (true) {
- try {
- int val = queue.take();
- System.out.println("消费者消耗:" + val);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- },"消费者");
- customer.start();
- Thread producer = new Thread(new Runnable() {
- @Override
- public void run() {
- Random random = new Random();
- while (true) {
- try {
- int num = random.nextInt(1000);
- System.out.println("生产者生产:" + num);
- queue.put(num);
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- },"生产者");
- producer.start();
- customer.join();
- producer.join();
- }
通过“循环队列”的方式来实现
使用 synchronized 进行加锁控制
put 插入元素的时候,判定如果队列满了,就进行 wait (要在循环中wait,被唤醒时不一定队列就不满,因为同时可能唤醒了多个进程)
take 取出元素时,判定如果队列为空,就进行 wait

- public static void main(String[] args) throws InterruptedException {
- BlockingQueue queue = new BlockingQueue();
- Thread customer = new Thread(new Runnable() {
- @Override
- public void run() {
- while (true) {
- try {
- int val = queue.take();
- System.out.println("消费者消耗:" + val);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- },"消费者");
- customer.start();
- Thread producer = new Thread(new Runnable() {
- @Override
- public void run() {
- Random random = new Random();
- while (true) {
- try {
- int num = random.nextInt(1000);
- System.out.println("生产者生产:" + num);
- queue.put(num);
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- },"生产者");
- producer.start();
- customer.join();
- producer.join();
- }
-
- static class BlockingQueue {
- private int[] items = new int[1000];
- private volatile int size;
- private int head;
- private int tail;
-
- public void put(int value) throws InterruptedException {
- synchronized (this) {
- while (size == items.length) {
- wait();
- }
- items[tail] = value;
- tail = (tail + 1) % items.length;
- size++;
- notifyAll();
- }
- }
-
- public int take() throws InterruptedException {
- synchronized (this) {
- while (size == 0) {
- wait();
- }
- int res = items[head];
- head = (head + 1) % items.length;
- size--;
- notifyAll();
- return res;
- }
- }
- }
测试:

定时器也是软件开发中的一个重要组件,类似于一个闹钟,达到一个设定的时间后,就执行某个指定好的代码

标准库中的提供了一个 Timer 类。Timer 类的核心方法为 schedule
schedule 包含了两个参数
第一个参数指定即将要执行的任务代码
第二个参数指定多长时间之后执行(单位是毫秒)
- public static void main(String[] args) {
- Timer timer = new Timer();
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- System.out.println("hello");
- }
- },2000);
- }
定时器的构成:
一个带优先级的阻塞队列
为啥要带优先级?
因为阻塞队列中的任务都有各自执行的时刻(delay),最先执行的任务一定是 delay 最小的,使用带优先级队列就可以高效地把这个 delay 最小的任务找出来
队列中地每个元素是一个 task 对象
task 中带有一个属性,队首元素就是即将执行地task
同时带有一个worker 线程一直扫描队首元素,看队首元素是否需要执行
- public class Timer {
- public void schedule(Runnable command,long after) {
- //TODO
- }
- }

- static class Task implements Comparable<Task> {
- private Runnable command;
- private long time;
-
- public Task(Runnable command,long time) {
- this.command = command;
- this.time = System.currentTimeMillis() + time;
- }
-
- public void run() {
- command.run();
- }
-
- @Override
- public int compareTo(Task o) {
- return (int) (time - o.time);
- }
- }

- PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
- public void schedule(Runnable command,long after) {
- Task task = new Task(command,after);
- queue.offer(task);
- }

- class Worker extends Thread{
- @Override
- public void run() {
- while (true) {
- try {
- Task task = queue.take();
- long cur = System.currentTimeMillis();
- if (task.time > cur) {
- queue.put(task);
- } else {
- task.run();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- break;
- }
- }
- }
- }

![]()

完整代码:
- public class Timer {
-
- private Object mailBox = new Object();
- PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
-
- public void schedule(Runnable command,long after) {
- Task task = new Task(command,after);
- queue.offer(task);
- synchronized (mailBox) {
- notify();
- }
- }
-
- class Worker extends Thread{
- @Override
- public void run() {
- try {
- Task task = queue.take();
- long cur = System.currentTimeMillis();
- if (task.time > cur) {
- queue.put(task);
- synchronized (mailBox) {
- mailBox.wait(task.time - cur);
- }
- } else {
- task.run();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- static class Task implements Comparable<Task> {
- private Runnable command;
- private long time;
-
- public Task(Runnable command,long time) {
- this.command = command;
- this.time = System.currentTimeMillis() + time;
- }
-
- public void run() {
- command.run();
- }
-
- @Override
- public int compareTo(Task o) {
- return (int) (time - o.time);
- }
- }
- }