[Java EE] 多线程(四):线程安全问题(下)

发布于:2024-04-28 ⋅ 阅读:(25) ⋅ 点赞:(0)

1.5 volatile关键字

我们在了解这个关键字之前,我们首先要把产生线程安全的第4个原因补齐,我们来说说由于内存可见性引起的线程安全问题.
我们来看下面这样一段代码:

import java.util.Scanner;

public class Demo16 {
    public static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (count == 0) {
                ;
            }
            System.out.println("count的值被修改");
        });
        Thread thread1 = new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            count = scanner.nextInt();
        });
        thread.start();
        Thread.sleep(1000);
        thread1.start();
    }
}

由上述代码的逻辑,我们预期的结果是:在控制台的地方输入了一个不为0的数字的时候,上面的循环条件不满足,跳出循环,打印"count的值被修改",但是我们运行起来发现:
在这里插入图片描述
输入了不为0的值之后,毛都没有!!
为什么会出现这种情况呢?我们首先要了解一下Java中的内存模型(JMM),即Java虚拟机规范中定义的Java内存模型.
在这里插入图片描述
设计这种内存模型的目的就是为了保证:屏蔽掉各种硬件和操作系统的访问差异,避免由于操作系统不同和硬件结构的不同而引起的不兼容,真正做到"一次编译,到处运行".

  • 线程之间的共享变量存在主内存(Main Memory).(硬件角度总真正的内存空间)
  • 每⼀个线程都有自己的"⼯作内存"(Working Memory).(硬件角度的CPU中的寄存器)
  • 线程想要读取一个共享变量的时候,需要先从主内存中拷贝到工作内存中.
  • 线程想要修改一个共享变量的时候,先修改工作内存中的副本,再同步回主内存中.

但是当计算机发现每次从主内存中拷贝数据到工作内存中时,每次拷贝的数据都是一样的,而且工作内存的访问要比主内存的访问快好几个数量级,这就使得计算机不得不做出优化操作,每次读取变量的时候,把拷贝这一步优化掉了,直接读取的是工作内存中的数据,这就使得在另一个线程在主内存中修改这个共享变量的时候,另一个线程读取不到,也就无法改变工作内存中的数据.
但是我们在循环中加上一个print操作的时候,我们会惊奇地发现,循环可以停下来了:

import java.util.Scanner;
public class Demo17 {
    public static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (count == 0) {
                System.out.println("tread");//IO输出比count判断慢得多
            }
            System.out.println("count的值被修改");
        });
        Thread thread1 = new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            count = scanner.nextInt();
        });
        thread.start();
        Thread.sleep(1000);
        thread1.start();
    }
}

在这里插入图片描述
这又是为什么呢?是因为由于拷贝操作时内存方面的操作,速度肯定又要比IO操作快好几个数量级.而IO操作每次执行的结果注定是不同的,这就使得JVM不可以优化掉IO操作,即然IO操作都优化不到,比他快好几个数量级的拷贝操作肯定优化不到.

举例说明:年会不能停
有请助教:潘妮,马杰克,胡建林,杰弗瑞.
假如现在没有胡建林,现在潘妮就相当于主内存与工作内存中的拷贝操作,马杰克就相当于直接从工作内存中读取的操作.如今杰弗瑞要裁员,由于马杰克的工作效率和工作能力比潘妮大上好几个数量级,裁员的时候优先裁的就是潘妮,但是现在歪打正着混进个胡建林,就相当于IO操作,由于胡建林是靠着"关系"进入的众和集团,即使胡建林干活再慢,也不可以裁掉,即然比潘妮干活慢的胡建林都裁不掉,何谈裁潘妮.
在这里插入图片描述

现在如果没有IO操作,还想要while循环停下来,我们就可以引入volatile关键字来对变量进行修饰.告诉JVM,该变量必须每次都到主内存中读取,不可以进行优化操作,就相当于告诉老板,裁员的时候请不要裁到大动脉!!!

import java.util.Scanner;

public class Demo18 {
    public static volatile int count = 0;//使用volatile告诉编译器该变量不可优化
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (count == 0) {
                ;
            }
            System.out.println("count的值被修改");
        });
        Thread thread1 = new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            count = scanner.nextInt();
        });
        thread.start();
        Thread.sleep(1000);
        thread1.start();
    }
}

在这里插入图片描述
但是我们需要注意的是:volatile不保证原子性

public class Demo21 {
    public static volatile int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                count++;
            }
        });
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                count++;
            }
        });
        thread.start();
        thread1.start();
        thread.join();
        thread1.join();
        System.out.println(count);
    }
}

在这里插入图片描述
我们看到,即使给count变量加了volatile关键字,还是会存在线程安全问题.

1.6 wait与notify–>线程的等待通知机制

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

举例说明:光与影
有请助教:黑子哲也,青峰大辉,火神大我
在与漂亮国的对决中,他们像拿到一个二分球,就先需要大辉先抢球,之后传球给黑子,黑子通过回旋一击,使得篮球改变运动轨迹,之后通过大我的扣篮完成完美一击.
他们中间的先后顺序,但凡慢了一步,或者是快了一步,都会丢失这2分.
在这里插入图片描述
在这里插入图片描述

完成这里的协调工作,需要涉及到三个方法:

  • wait()/wait(time):让线程进入等待状态
  • notify()/notifyAll():唤醒在当前对象上等待的所有线程
    注意:这几个方法都是Object类的方法

1.6.1 wait()方法

wait做的事情:

  • 释放当前对象的锁
  • 使得当前线程进入阻塞等待状态
  • 满足一定条件被唤醒之后,尝试重新获取锁
    注意:wait要搭配synchronized使用,否者在wait()方法解锁的时候,找不到对应的锁,就会抛出异常.
    wait结束等待的条件:
  • 其他线程使用调用notify方法唤醒该线程.
  • wait时间超时.
  • 其他线程调用该线程的interrupted方法,导致线程被强制唤醒,抛出异常.

1.6.2 notify()方法

notify⽅法是唤醒等待的线程.
• ⽅法notify()也要在同步⽅法或同步块中调⽤,该⽅法是⽤来通知那些可能等待该对象的对象锁的其它线程,对其发出通知notify,并使它们重新获取该对象的对象锁。
• 如果有多个线程等待,则有线程调度器随机挑选出⼀个呈wait状态的线程。(并没有"先来后到")
• 在notify()⽅法后,当前线程不会⻢上释放该对象锁,要等到执⾏notify()⽅法的线程将程序执⾏
,也就是退出同步代码块之后才会释放对象锁。
使用示例:

public class Demo19 {
    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        Thread thread = new Thread(()->{
            synchronized (object){
                System.out.println("等待开始");
                try {
                    object.wait();//1.解锁,此时tread1才可以加锁 2.阻塞等待 3.唤醒之后再尝试获取锁 4.唤醒之后tread1未解除锁,阻塞
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("等待结束");//所以等待结束的打印一定在唤醒结束之后
            }
        });
        Thread thread1 = new Thread(()->{
            synchronized (object){
                System.out.println("唤醒开始");
                object.notify();
                System.out.println("唤醒结束");
            }
        });
        thread.start();
        Thread.sleep(1000);
        thread1.start();
    }
}

注意:在tread启动之后,必须sleep1s,由于线程调度的随机性,不加的话很可能先调度tread1现成,这样notify就会被wait错过

1.6.3 notifyAll()方法

上述notify方法只能随机唤醒一个线程:

public class Demo20 {
    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        Thread thread = new Thread(()->{
            synchronized (object){
                System.out.println("等待开始");
                try {
                    object.wait();//1.解锁,此时tread1才可以加锁 2.阻塞等待 3.唤醒之后再尝试获取锁 4.唤醒之后tread1未解除锁,阻塞
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("等待结束");//所以等待结束的打印一定在唤醒结束之后
            }
        });
        Thread thread2 = new Thread(()->{
            synchronized (object){
                System.out.println("等待开始1");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("等待结束1");
            }
        });
        Thread thread1 = new Thread(()->{
            synchronized (object){
                System.out.println("唤醒开始");
                object.notify();
                System.out.println("唤醒结束");
            }
        });
        thread.start();
        thread2.start();
        Thread.sleep(1000);
        thread1.start();
    }
}

运行结果:只唤醒了tread线程
在这里插入图片描述
如果想要一次性唤醒所有线程,就要用到notifyAll()方法:

public class Demo20 {
    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        Thread thread = new Thread(()->{
            synchronized (object){
                System.out.println("等待开始");
                try {
                    object.wait();//1.解锁,此时tread1才可以加锁 2.阻塞等待 3.唤醒之后再尝试获取锁 4.唤醒之后tread1未解除锁,阻塞
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("等待结束");//所以等待结束的打印一定在唤醒结束之后
            }
        });
        Thread thread2 = new Thread(()->{
            synchronized (object){
                System.out.println("等待开始1");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("等待结束1");
            }
        });
        Thread thread1 = new Thread(()->{
            synchronized (object){
                System.out.println("唤醒开始");
                object.notifyAll();
                System.out.println("唤醒结束");
            }
        });
        thread.start();
        thread2.start();
        Thread.sleep(1000);
        thread1.start();
    }
}

运行结果:线程全部被唤醒
在这里插入图片描述
在两个线程全部被唤醒之后,由于唤醒之后线程会尝试重新获取锁,tread和tread2还是会发生锁竞争.

举例:面试
有请助教:滑稽老铁
notify()方法:
在这里插入图片描述
notifyAll()方法:
在这里插入图片描述