This article brings you relevant knowledge about java, which mainly introduces issues related to multi-threading, including thread installation, thread locking and thread insecurity reasons, thread Safety standard categories and other content, I hope it will be helpful to everyone.
Recommended study: "java Video Tutorial"
This article introduces the thread safety issues in Java multi-threading The security issues here do not refer to security issues caused by hackers. Thread safety issues refer to bugs in programs caused by multi-threaded preemptive execution.
First of all, we need to understand that thread scheduling in the operating system is preemptive, or random. , which causes the execution order of threads to be uncertain when thread scheduling is executed. Some codes have different execution orders and will not affect the program running results. However, there are also some codes that change the execution order and the rewritten running results will be affected. This is Code that causes bugs in the program when multiple threads are concurrent is called thread-unsafe code. This is a thread safety issue.
Below, we will introduce a typical example of thread safety problem, the integer self-increment problem.
One day, the teacher assigned such a problem: use two threads to increment the variable count
10
Ten thousand times, each thread undertakes the self-increment task 5
ten thousand times, and the initial value of the variable count
is 0
.
This question is very simple. We can also calculate the final result verbally. The answer is 10
million.
Xiao Ming worked very quickly and quickly wrote the following piece of code:
class Counter { private int count; public void increase() { ++this.count; } public int getCount() { return this.count; }}public class Main11 { private static final int CNT = 50000; private static final Counter counter = new Counter(); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { for (int i = 0; i { for (int j = 0; j <p> Logically speaking, the result should be <code>10</code> million. Let’s take a look at the running results: <br><img src="https://img.php.cn/upload/article/000/000/067/5a3746e6458021f78f91292b5a885487-1.png" alt="Lets talk about the thread safety issues of Java multithreading"><br> The running result is smaller than <code>10</code>. You can try to run the program and you will find that the result is different every time, but in most cases, the result is The values will all be smaller than expected. Let's analyze why this is the case. </p><h2><strong>2. Reasons for thread locking and thread insecurity</strong></h2><h2>2.1 Case analysis</h2><p> Above we used multi-threading to run a program and put a The variable with a variable value of 0 is incremented 100,000 times, but the final actual result is smaller than our expected result. The reason is that the order of thread scheduling is random, causing the self-increment instruction sets to intersect between threads, resulting in two self-increases during runtime. Increment, but the value only increments once, so the result obtained will be smaller. </p><p>We know that an auto-increment operation can include the following instructions: </p><ol> <li>Load the value of the variable in the memory into the register. You may wish to record this operation as <code>load</code>. </li> <li>To perform an auto-increment operation in a register, you may wish to record the operation as <code>add</code>. </li> <li>Save the register value to memory. You may wish to record this operation as <code>save</code>. </li> </ol><p> Let’s draw a timeline to summarize several common situations: </p><p><strong>Case 1: </strong> Inter-thread instruction set, no intersection, running results As expected, register A in the figure represents the register used by thread 1, and register B represents the register used by thread 2. The same applies to the subsequent situations. <br><img src="https://img.php.cn/upload/article/000/000/067/1a7f0bb1b7c2552a80983e04b900dc15-2.png" alt="Lets talk about the thread safety issues of Java multithreading"><br><strong>Case 2: </strong> There is overlap in instruction sets between threads, and the running results are lower than expected. <br><img src="https://img.php.cn/upload/article/000/000/067/1a7f0bb1b7c2552a80983e04b900dc15-3.png" alt="Lets talk about the thread safety issues of Java multithreading"><br><strong>Case 3: </strong> The instruction sets between threads are completely crossed, and the actual results are lower than expected. <br><img src="https://img.php.cn/upload/article/000/000/067/4e482e48ea6191128516ca82417af3cf-4.png" alt="Lets talk about the thread safety issues of Java multithreading"><br> According to the situation we listed above, it is found that the running results are normal when there are no cross instructions when the thread is running, but once there is a cross, the results of the auto-increment operation will be less<code>1 </code>, from the above we can draw a conclusion, that is, since the auto-increment operation is not atomic, concurrent execution of multiple threads is likely to cause the execution of instructions to overlap, leading to thread safety issues. </p><p>So how to solve the above thread insecurity problem? Of course there is, that is to lock the object. </p><h2>2.2 Thread locking</h2><h3><strong>2.2.1 What is locking</strong></h3><p>In order to solve the thread safety problem caused by "preemptive execution", We can lock the object of operation. When a thread gets the lock of the object, it will lock the object. If other threads need to perform the task of the object, they need to wait for the thread to finish running the task of the object. can be executed. </p><p>举个例子,假设要你去银行的ATM机存钱或者取款,每台ATM机一般都在一间单独的小房子里面,这个小房子有一扇门一把锁,你进去使用ATM机时,门会自动的锁上,这个时候如果有人要来取款,那它得等你使用完并出来它才能进去使用ATM,那么这里的“你”相当于线程,ATM相当于一个对象,小房子相当于一把锁,其他的人相当于其他的线程。<br><img src="https://img.php.cn/upload/article/000/000/067/4e482e48ea6191128516ca82417af3cf-5.png" alt="Lets talk about the thread safety issues of Java multithreading"><br><img src="https://img.php.cn/upload/article/000/000/067/6e6c80338fcb268f141a907ecdcadb51-6.png" alt="Lets talk about the thread safety issues of Java multithreading"><br> 在java中最常用的Lets talk about the thread safety issues of Java multithreading操作就是使用<code>synchronized</code>关键字进行Lets talk about the thread safety issues of Java multithreading。</p><h3>2.2.2如何Lets talk about the thread safety issues of Java multithreading</h3><p>synchronized 会起到互斥效果, 某个线程执行到某个对象的 synchronized 中时, 其他线程如果也执行到同一个对象 synchronized 就会阻塞等待。<br> 线程进入 synchronized 修饰的代码块, 相当于<code>Lets talk about the thread safety issues of Java multithreading</code>,退出 synchronized 修饰的代码块, 相当于 <code>解锁</code>。</p><p>java中的Lets talk about the thread safety issues of Java multithreading操作可以使用<code>synchronized</code>关键字来实现,它的常见使用方式如下:</p><p><strong>方式1:</strong> 使用<code>synchronized</code>关键字修饰普通方法,这样会使方法所在的对象加上一把锁。<br> 例如,就以上面自增的程序为例,尝试使用<code>synchronized</code>关键字进行Lets talk about the thread safety issues of Java multithreading,如下我对<code>increase</code>方法进行了Lets talk about the thread safety issues of Java multithreading,实际上是对某个对象Lets talk about the thread safety issues of Java multithreading,此锁的对象就是<code>this</code>,本质上Lets talk about the thread safety issues of Java multithreading操作就是修改<code>this</code>对象头的标记位。</p><pre class="brush:php;toolbar:false">class Counter { private int count; synchronized public void increase() { ++this.count; } public int getCount() { return this.count; }}
多线程自增的main方法如下,后面会以相同的栗子介绍synchronized
的其他用法,后面就不在列出这段代码了。
public class Main11 { private static final int CNT = 50000; private static final Counter counter = new Counter(); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { for (int i = 0; i { for (int j = 0; j <p>看看Lets talk about the thread safety issues of Java multithreading:<br><img src="https://img.php.cn/upload/article/000/000/067/6e6c80338fcb268f141a907ecdcadb51-7.png" alt="Lets talk about the thread safety issues of Java multithreading"><br><strong>方式2:</strong> 使用<code>synchronized</code>关键字对代码段进行Lets talk about the thread safety issues of Java multithreading,但是需要显式指定Lets talk about the thread safety issues of Java multithreading的对象。<br> 例如:</p><pre class="brush:php;toolbar:false">class Counter { private int count; public void increase() { synchronized (this){ ++this.count; } } public int getCount() { return this.count; }}
Lets talk about the thread safety issues of Java multithreading:
方式3: 使用synchronized
关键字修饰静态方法,相当于对当前类的类对象进行Lets talk about the thread safety issues of Java multithreading。
class Counter { private static int count; synchronized public static void increase() { ++count; } public int getCount() { return this.count; }}
Lets talk about the thread safety issues of Java multithreading:
常见的用法差不多就是这些,对于线程Lets talk about the thread safety issues of Java multithreading(线程拿锁),如果两个线程同时拿一个对象的锁,就会产生锁竞争,两个线程同时拿两个不同对象的锁不会产生锁竞争。
对于synchronized
这个关键字,它的英文意思是同步,但是同步在计算机中是存在多种意思的,比如在多线程中,这里同步的意思是“互斥”;而在IO或网络编程中同步指的是“异步”,与多线程没有半点的关系。
synchronized 的工作过程:
lock
unlock
synchronized 同步块对同一条线程来说是可重入的,不会出现自己把自己锁死的问题,即死锁问题,关于死锁后续文章再做介绍。
综上,synchronized关键字Lets talk about the thread safety issues of Java multithreading有如下性质:互斥性,刷新内存性,可重入性。
synchronized关键字也相当于一把监视器锁monitor lock,如果不Lets talk about the thread safety issues of Java multithreading,直接使用wait
方法(一种线程等待的方法,后面细说),会抛出Lets talk about the thread safety issues of Java multithreading,引发这个异常的原因就是没有Lets talk about the thread safety issues of Java multithreading。
对自增那个代码上锁后,我们再来分析一下为什么加上了所就线程安全了,先列代码:
class Counter { private int count; synchronized public void increase() { ++this.count; } public int getCount() { return this.count; }}public class Main11 { private static final int CNT = 50000; private static final Counter counter = new Counter(); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { for (int i = 0; i { for (int j = 0; j <p>多线程并发执行时,上一次就分析过没有指令集交叉就不会出现问题,因此这里我们只讨论指令交叉后,Lets talk about the thread safety issues of Java multithreading操作是如何保证线程安全的,不妨记Lets talk about the thread safety issues of Java multithreading为<code>lock</code>,解锁为<code>unlock</code>,两个线程运行过程如下:<br> 线程1首先拿到目标对象的锁,对对象进行Lets talk about the thread safety issues of Java multithreading,处于<code>lock</code>状态,当线程2来执行自增操作时会发生阻塞,直到线程1的自增操作完毕,处于<code>unlock</code>状态,线程2才会就绪取执行线程2的自增操作。<br><img src="https://img.php.cn/upload/article/000/000/067/aacb0e52e264f65d74e598d37852834f-10.png" alt="Lets talk about the thread safety issues of Java multithreading"><br> Lets talk about the thread safety issues of Java multithreading后线程就是串行执行,与单线程其实没有很大的区别,那多线程是不是没有用了呢?但是对方法Lets talk about the thread safety issues of Java multithreading后,线程运行该方法才会Lets talk about the thread safety issues of Java multithreading,运行完该方法就会自动解锁,况且大部分操作并发执行是不会造成线程安全的,只有少部分的修改操作才会有可能导致线程安全问题,因此整体上多线程运行效率还是比单线程高得多。</p><h2>2.3线程不安全的原因</h2><p>首先,线程不安全根源是线程间的调度充满随机性,导致原有的逻辑被改变,造成线程不安全,这个问题无法解决,无可奈何。</p><p>多个线程针对同一资源进行写(修改)操作,并且针对资源的修改操作不是原子性的,可能会导致线程不安全问题,类似于数据库的事务。</p><p>由于编译器的优化,内存可见性无法保证,就是当线程频繁地对同一个变量进行读操作时,会直接从寄存器上读值,不会从内存上读值,这样内存的值修改时,线程就感知不到该变量已经修改,会导致线程安全问题(这是编译器优化的结果,现代的编译器都有类似的优化不止于Java),因为相比于寄存器,从内容中读取数据的效率要小的多,所以编译器会尽可能地在逻辑不变的情况下对代码进行优化,单线程情况下是不会翻车的,但是多线程就不一定了,比如下面一段代码:</p><pre class="brush:php;toolbar:false">import java.util.Scanner;public class Main12 { private static int isQuit; public static void main(String[] args) { Thread thread = new Thread(() -> { while (isQuit == 0) { } System.out.println("线程thread执行完毕!"); }); thread.start(); Scanner sc = new Scanner(System.in); System.out.println("请输入isQuit的值,不为0线程thread停止执行!"); isQuit = sc.nextInt(); System.out.println("main线程执行完毕!"); }}
Lets talk about the thread safety issues of Java multithreading:
我们从Lets talk about the thread safety issues of Java multithreading可以知道,输入isQuit
后,线程thread
没有停止,这就是编译器优化导致线程感知不到内存可见性,从而导致线程不安全。
我们可以使用Lets talk about the thread safety issues of Java multithreading
关键字保证内存可见性。
我们可以使用Lets talk about the thread safety issues of Java multithreading
关键字修饰isQuit
来保证内存可见性。
import java.util.Scanner;public class Main12 { Lets talk about the thread safety issues of Java multithreading private static int isQuit; public static void main(String[] args) { Thread thread = new Thread(() -> { while (isQuit == 0) { } System.out.println("线程thread执行完毕!"); }); thread.start(); Scanner sc = new Scanner(System.in); System.out.println("请输入isQuit的值,不为0线程thread停止执行!"); isQuit = sc.nextInt(); System.out.println("main线程执行完毕!"); }}
Lets talk about the thread safety issues of Java multithreading:
synchronized与Lets talk about the thread safety issues of Java multithreading关键字的区别:synchronized
关键字能保证原子性,但是是否能够保证内存可见性要看情况(上面这个栗子是不行的),而Lets talk about the thread safety issues of Java multithreading
关键字只能保证内存可见性不能保证原子性。
保证内存可见性就是禁止编译器做出如上的优化而已。
import java.util.Scanner;public class Main12 { private static int isQuit; //锁对象 private static final Object lock = new Object(); public static void main(String[] args) { Thread thread = new Thread(() -> { synchronized (lock) { while (isQuit == 0) { } System.out.println("线程thread执行完毕!"); } }); thread.start(); Scanner sc = new Scanner(System.in); System.out.println("请输入isQuit的值,不为0线程thread停止执行!"); isQuit = sc.nextInt(); System.out.println("main线程执行完毕!"); }}
Lets talk about the thread safety issues of Java multithreading:
编译器优化除了导致内存可见性感知不到的问题,还有指令重排序也会导致线程安全问题,指令重排序也是编译器优化之一,就是编译器会智能地(保证原有逻辑不变的情况下)调整代码执行顺序,从而提高程序运行的效率,单线程没问题,但是多线程可能会翻车,这个原因了解即可。
Java 标准库中很多都是线程不安全的。这些类可能会涉及到多线程修改共享数据, 又没有任何Lets talk about the thread safety issues of Java multithreading措施。例如,ArrayList,LinkedList,HashMap,TreeMap,HashSet,TreeSet,StringBuilder。
但是还有一些是线程安全的,使用了一些锁机制来控制,例如,Vector (不推荐使用),HashTable (不推荐使用),ConcurrentHashMap (推荐),StringBuffer。
还有的虽然没有Lets talk about the thread safety issues of Java multithreading, 但是不涉及 “修改”, 仍然是线程安全的,例如String。
在线程安全问题中可能你还会遇到JMM模型,在这里补充一下,JMM其实就是把操作系统中的寄存器,缓存和内存重新封装了一下,其中在JMM中寄存器和缓存称为工作内存,内存称为主内存。
其中缓存分为一级缓存L1,二级缓存L2和三级缓存L3,从L1到L3空间越来越大,最大也比内存空间小,最小也比寄存器空间大,访问速度越来越慢,最慢也比内存的访问速度快,最快也没有寄存器访问快。
除了Thread类中的能够实现线程等待的方法,如join
,sleep
,在Object类中也提供了相关线程等待的方法。
序号 | 方法 | 说明 |
---|---|---|
1 | public final void wait() throws InterruptedException | 释放锁并使线程进入WAITING状态 |
2 | public final native void wait(long timeout) throws InterruptedException; | 相比于方法1,多了一个最长等待时间 |
3 | public final void wait(long timeout, int nanos) throws InterruptedException | 相比于方法2,等待的最长时间精度更大 |
4 | public final native void notify(); | 唤醒一个WAITING状态的线程,并Lets talk about the thread safety issues of Java multithreading,搭配wait方法使用 |
5 | public final native void notifyAll(); | 唤醒所有处于WAITING状态的线程,并Lets talk about the thread safety issues of Java multithreading(很可能产生锁竞争),搭配wait方法使用 |
上面介绍synchronized
关键字的时候,如果不对线程Lets talk about the thread safety issues of Java multithreading会产生非法监视异常,我们来验证一下:
public class TestDemo12 { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("执行完毕!"); }); thread.start(); System.out.println("wait前"); thread.wait(); System.out.println("wait后"); }}
看看Lets talk about the thread safety issues of Java multithreading:
果然抛出了一个IllegalMonitorStateException
,因为wait
方法的执行步骤为:先释放锁,再使线程等待,你现在都没有Lets talk about the thread safety issues of Java multithreading,那如何释放锁呢?所以会抛出这个异常,但是执行notify
是无害的。
wait
方法常常搭配notify
方法搭配一起使用,前者能够释放锁,使线程等待,后者能获取锁,使线程继续执行,这套组合拳的流程图如下:
现在有两个任务由两个线程执行,假设线程2比线程1先执行,请写出一个多线程程序使任务1在任务2前面完成,其中线程1执行任务1,线程2执行任务2。
这个需求可以使用wait/notify
来实现。
class Task{ public void task(int i) { System.out.println("任务" + i + "完成!"); }}public class WiteNotify { //锁对象 private static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { synchronized (lock) { Task task1 = new Task(); task1.task(1); //通知线程2线程1的任务完成 System.out.println("notify前"); lock.notify(); System.out.println("notify后"); } }); Thread thread2 = new Thread(() -> { synchronized (lock) { Task task2 = new Task(); //等待线程1的任务1执行完毕 System.out.println("wait前"); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } task2.task(2); System.out.println("wait后"); } }); thread2.start(); Thread.sleep(10); thread1.start(); }}
Lets talk about the thread safety issues of Java multithreading:
推荐学习:《java视频教程》
The above is the detailed content of Let's talk about the thread safety issues of Java multithreading. For more information, please follow other related articles on the PHP Chinese website!