目錄
一、線程安全(重點)
1.線程安全演示
2.線程不安全的原因
1.線程是搶占式執行的(執行順序是隨機的)
2.多個線程同時修改了同一個變量
3.原子性
4.內存可見性
5.指令重排序(有序性)
二、解決線程不安全的問題
1.鎖的概念
2.synchronized
3.synchronized的特性
4.關于synchronized
5.使用單獨的鎖對象
6.synchronized使用示例
7.synchronized - 監視器鎖monitor lock
7.1synchronized的特性
1.互斥
2.可重入
3.可見性
8.volatile 關鍵字
一、線程安全(重點)
1.線程安全演示
/*** 線程安全演示*/public class Text03 {public static void main(String[] args) throws InterruptedException {// 初始化累加對象Counter counter = new Counter();// 創建兩個線程對一個變量進時累加// 線程1Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});// 線程2Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});// 啟動線程t1.start();t2.start();// 等待線程完成t1.join();t2.join();// 查看運行結果System.out.println("count = " + counter.count);}
}// 專門用來累加的類
class Counter {// 初始值是0public int count = 0;/*** 累加方法*/public void increase () {count++;}
}
//count = 68419
程序運行結果與預期值不一致,而且是一個錯誤的結果,而且我們的邏輯是正確的,這個現象所表現的問題稱為線程安全問題
2.線程不安全的原因
1.線程是搶占式執行的(執行順序是隨機的)
由于線程地執行順序無法人為控制,搶占式執行是造成線程安全問題的主要原因,而且我i們解決不了,完全是CPU自己調度,而且和CPU內核數有關
2.多個線程同時修改了同一個變量
多個線程修改同一個變量,會出現線程安全問題
多個線程修改不同變量,不會出行線程安全問題
一個線程修改一個變量,不會出現線程安全問題
3.原子性
要么全部執行,要么全部不執行
寫的count++對應多條CPU指令
1.從內存或寄存器中讀取count的值? ? ?LOAD
2.執行自增? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ADD
3.把計算結果寫回寄存器中? ? ? ? ? ? ? ? ?STORE
CPU執行指令,和代碼沒關系
由于執行CPU指令不是原子性的,導致這三條指令沒有執行完就被CPU調度走了
另外的線程加載到一個原始值
當兩個線程分別自增完成后,把值寫回內存時發生覆蓋現象
4.內存可見性
1.Java線程首先是從主內存讀取變量的值到自己工作內存
2.每個線程都有自己的工作內存,且工作內存間是隔離的
3.線程在自己的工作內存中把自己的值修改完成之后再把修改后的值寫回主內存
以上執行的count++操作,由于是兩個線程在在執行,每個線程都有自己的工作內存,且相互之間不可見,最終導致了線程安全問題
工作內存與線程之間是一一對應的(這是JVM規定的)
外存(磁盤)-->內存(運行過程被加載到內存)--> 寄存器(封裝到CPU中)
工作內存是JAVA層面對物理層面的關于程序所使用的到了寄存器的抽象
?如果通過某種方式讓線程之間可以相互通信,稱之為內存可見性
5.指令重排序(有序性)
?我們寫的代碼在編譯之后可能會與代碼對應的指令執行順序不同,這個過程就是指令重排序
JVM層面可能會重排, CPU執行指令時也可以重排
指令重排序必須要保證程序運行的結果是正確的? 單線程的環境里是沒有任何問題的 指令重排序在邏輯上互不影響
二、解決線程不安全的問題
事務的隔離級別是通過鎖和MVCC機制保證的
1.鎖的概念
線程A拿到了鎖,別的線程如果執行被鎖住的代碼,必須要等到線程A釋放鎖,如果線程A沒有釋放鎖,那么別的線程只能阻塞等待,這個狀態就是BLOCK
先拿鎖 --> 執行代碼 --> 釋放鎖 --> 下一個線程再拿鎖...
2.synchronized
可以為方法加鎖也? ? 可以為代碼加鎖
只解決原子性問題,它所修改的代碼有并行變成了串行
public class Text01 {public static void main(String[] args) throws InterruptedException {// 初始化累加對象Counter counter = new Counter();// 創建兩個線程對一個變量進時累加// 線程1Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});// 線程2Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});// 啟動線程t1.start();t2.start();// 等待線程完成t1.join();t2.join();// 查看運行結果System.out.println("count = " + counter.count);}
}// 專門用來累加的類
class Counter {// 初始值是0public int count = 0;/*** 累加方法*/public synchronized void increase () {count++;}
}
//count = 100000
t1先獲得了鎖,執行方法, 方法執行完成之后其它線程在獲取鎖?
這樣的情況是一個單線程運行狀態
是把多線程轉成了單線程,從而解決線程安全問題
解決方法單線程的執行問題,可以修改代碼塊? 把對共享變量的修改加鎖執行?
由于線程在執行邏輯之前要拿到鎖,當拿到鎖時,上一個線程已經執行完了所有的指令,并把修改的值刷回了主內存,當前線程讀到了永遠都是上一個線程修改后的值
t1釋放鎖之后,也有可能第二次循環時t1先于t2拿到鎖,因為線程時搶占式執行的
3.synchronized的特性
1.保證了原子性(通過加鎖來實現)
2.保證了內存有序性(通過串行執行實現)
3.不保證有序性
4.關于synchronized
1.被synchronized修飾的代碼會變成串行執行
2.synchronized可以修飾方法,也可以修飾代碼塊
3.被synchronized修飾的代碼并不是一次性在CPU執行完,而是中途可能被CPU調度走,當所有指令執行完成之后才會釋放鎖
4.只給一個線程加鎖,也會出現線程不安全問題
public class Text01 {public static void main(String[] args) throws InterruptedException {// 初始化累加對象Counter01 counter = new Counter01();// 創建兩個線程對一個變量進時累加// 線程1Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});// 線程2Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase1();}});// 啟動線程t1.start();t2.start();// 等待線程完成t1.join();t2.join();// 查看運行結果System.out.println("count = " + counter.count);}
}// 專門用來累加的類
class Counter01 {// 初始值是0public int count = 0;/*** 累加方法*/public synchronized void increase () {count++;}public void increase1 () {count++;}
}
//count = 81072
線程獲取鎖:
1.如果只有與一個線程A,那么直接可以獲取鎖,沒有鎖競爭
2.線程A,B共同搶一把鎖的是時候,存在鎖競爭,誰先拿到就先執行自己的邏輯,另一個線程阻塞等待,等到持有鎖的線程釋放所之后,再參與競爭鎖
3.線程A,B競爭的不是同一把所的時候,他們沒有競爭關系
5.使用單獨的鎖對象
public class Text02 {public static void main(String[] args) throws InterruptedException {Counter02 counter = new Counter02();Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});t1.start();t2.start();t1.join();t2.join();System.out.println("count:" + counter.count);}
}class Counter02 {// 初始值為0public static int count = 0;// 單獨定義一個對象作為鎖對象用Object locker = new Object();/*** 累加方法**/public void increase () {// 只定義鎖代碼塊synchronized (locker) {count++;}}
}
// count : 100000
Counter中有一個locker,每創建一個counter都會初始化一個對象內部的成員變量locker
/*** 在多個實例中在使用鎖對象*/public class Text03 {public static void main(String[] args) throws InterruptedException {Counter03 counter1 = new Counter03();Counter03 counter2 = new Counter03();Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter1.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter2.increase();}});t1.start();t2.start();t1.join();t2.join();System.out.println("count:" + counter1.count);}
}class Counter03 {// 初始值為0public static int count = 0;// 單獨定義一個對象作為鎖對象用Object locker = new Object();/*** 累加方法**/public void increase () {// 只定義鎖代碼塊synchronized (locker) {count++;}}
}
//count:95487
每個counter中都有一個locker 兩個線程的鎖對象是不同的,不存在鎖競爭關系
/*** 單個實例中,創建兩個方法,使用同一個鎖對象*/public class Text04 {public static void main(String[] args) throws InterruptedException {Counter04 counter = new Counter04();Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase1();}});t1.start();t2.start();t1.join();t2.join();System.out.println("count:" + counter.count);}
}class Counter04 {// 初始值為0public static int count = 0;// 單獨定義一個對象作為鎖對象用Object locker = new Object();/*** 累加方法**/public void increase () {// 只定義鎖代碼塊synchronized (locker) {count++;}}public void increase1 () {// 只定義鎖代碼塊synchronized (locker) {count++;}}
}
//count:100000
locker是同一個對象,會產生鎖競爭關系
/*** 使用靜態全局變量*/
public class Text05 {public static void main(String[] args) throws InterruptedException {Counter05 counter = new Counter05();Counter05 counter1 = new Counter05();Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter1.increase();}});t1.start();t2.start();t1.join();t2.join();System.out.println("count:" + counter.count);}
}class Counter05 {// 初始值為0public static int count = 0;// 全局變量,屬于類對象static Object locker = new Object();/*** 累加方法**/public void increase () {// 只定義鎖代碼塊synchronized (locker) {count++;}}
}
//count:100000
類對象是全局唯一,產生鎖競爭
public class Text06 {public static void main(String[] args) throws InterruptedException {Counter05 counter = new Counter05();Counter05 counter1 = new Counter05();Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter1.increase();}});t1.start();t2.start();t1.join();t2.join();System.out.println("count:" + counter.count);}
}class Counter06 {// 初始值為0public static int count = 0;/*** 累加方法**/public void increase () {// 只定義鎖代碼塊synchronized (Counter06.class) {count++;}}
}
//count:100000
public class Text07 {public static void main(String[] args) throws InterruptedException {Counter05 counter = new Counter05();Counter05 counter1 = new Counter05();Thread t1 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 50000; i++) {counter1.increase();}});t1.start();t2.start();t1.join();t2.join();System.out.println("count:" + counter.count);}
}class Counter07 {// 初始值為0public static int count = 0;/*** 累加方法**/public void increase () {// 只定義鎖代碼塊synchronized (String.class) {count++;}}
}
//count:100000
任何一個對象都可以作為鎖對象
只能多個線程訪問的鎖對象是同一個,那么他們就存在競爭關系,否則就沒有競爭關系
6.synchronized使用示例
7.synchronized - 監視器鎖monitor lock
7.1synchronized的特性
1.互斥
一個線程獲取了鎖之后,其他線程必須要阻塞等待
只有當持有鎖的線程把鎖釋放了之后,所有的線程再去競爭鎖
2.可重入
package demo3;public class Text1 {public static void main(String[] args) throws InterruptedException {Counter1 counter1 = new Counter1();Thread t1 = new Thread(() -> {for (int i = 0; i < 5000; i++) {counter1.increase();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 5000; i++) {counter1.increase();}});t1.start();t2.start();t1.join();;t2.join();System.out.println("count = " + counter1.count);}
}class Counter1 {public static int count = 0;/*** 累加方法*/public synchronized void increase () {increase1();}private synchronized void increase1() {increase2();}private void increase2() {synchronized (this) {count++;}}
}
// count = 10000
3.可見性
通過結果來看達到內存可見性的目的,但是是通過原子性來實現的
8.volatile 關鍵字
package demo3;import java.util.Scanner;/*** 創建兩個線程* 1. 第一個線程, 不停的執行自己的任務* 2. 第二個線程,輸入一個停止標識,使第一個線程退出*/
public class Text2 {// 退出標識static int flag = 0;public static void main(String[] args) {Thread t1 = new Thread(() -> {System.out.println(Thread.currentThread().getName() + "線程啟動...");while (flag == 0) {// 不停的去循環, 處理任務}System.out.println(Thread.currentThread().getName() + "線程退出...");}, "t1");// 啟動線程t1.start();// 輸入停止標識Thread t2 = new Thread(() -> {System.out.println(Thread.currentThread().getName() + "'線程啟動...");Scanner scanner = new Scanner(System.in);System.out.println("請輸入一個整數:>");flag = scanner.nextInt();System.out.println(Thread.currentThread().getName() + "線程退出...");}, "t2");// 啟動線程t2.start();}
}
/*
t2'線程啟動...
t1線程啟動...
請輸入一個整數:>
1
t2線程退出...
*/
t2線程正常結束,并且修改了flag變量的值?
但是t1線程沒有結束,整個進程頁沒有結束
結果不及預期,線程安全問題產生
package demo3;import java.util.Scanner;/*** 創建兩個線程* 1. 第一個線程, 不停的執行自己的任務* 2. 第二個線程,輸入一個停止標識,使第一個線程退出*/
public class Text2 {// 退出標識static volatile int flag = 0;public static void main(String[] args) {Thread t1 = new Thread(() -> {System.out.println(Thread.currentThread().getName() + "線程啟動...");while (flag == 0) {// 不停的去循環, 處理任務}System.out.println(Thread.currentThread().getName() + "線程退出...");}, "t1");// 啟動線程t1.start();// 輸入停止標識Thread t2 = new Thread(() -> {System.out.println(Thread.currentThread().getName() + "'線程啟動...");Scanner scanner = new Scanner(System.in);System.out.println("請輸入一個整數:>");flag = scanner.nextInt();System.out.println(Thread.currentThread().getName() + "線程退出...");}, "t2");// 啟動線程t2.start();}
}
/*
t2'線程啟動...
t1線程啟動...
請輸入一個整數:>
1
t2線程退出...
t1線程退出...
*/
解決了內存可見性
解決了有序性
不保證原子性
多個線程之間涉及的共享變量,如果只存在修改的邏輯,只管加volatile
面試題:JMM如何實現原子性,可見性,有序性
synchronized實現了原子性,由于是串行從而也實現了可見性
volatile真正實現了內存可見性,有序性(使用了內存屏障)