解決執行緒的安全問題
上一篇博客執行緒安全問題
1.synchronized 關鍵字-監視器鎖monitor lock
synchronized的底層是使用作業系統的mutex lock實作的,
- 當執行緒釋放鎖時,JMM會把該執行緒對應的作業記憶體中的共享變數重繪到主記憶體中;
- 當執行緒獲取鎖時,JMM會把該執行緒對應的本地記憶體置為無效,從而使得被監視器保護的臨界區代碼必須從主記憶體中讀取共享變數;
1.作為方法的修飾符——方法的定義前面
synchronized int add(int a,int b){...}
synchronized static int add(int a,int b){...}
2.作為同步代碼塊
synchronized(物件的參考){
......
}
3.代碼演示
/**
* synchronized的語法使用示例
*/
public class ThreadDemo {
//同步方法
synchronized int add(int a,int b){
return 0;
}
synchronized static void sayHello(){
}
//同步代碼塊——能出現陳述句的地方
static void someMethod() {
Object object = new Object();
synchronized (object) {
}
}
}
2.用synchronized 解決上一篇博客中代碼的執行緒安全問題
public class ThreadDemo2 {
private static int n = 0;
private static final int COUNT = 100000;
static class Adder extends Thread{
@Override
public void run() {
for (int i = 0;i < COUNT;i++){
synchronized (Adder.class){
n++;
}
}
}
}
static class Suber extends Thread{
@Override
public void run() {
for (int i = 0;i < COUNT;i++){
synchronized (Adder.class){//一定和上面的加同一把鎖
n--;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Adder();
Thread t2 = new Suber();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(n);
}
}
3.volatile 關鍵字
修飾的共享變數,可以保證可見性**,部分保證順序性**;
class ThreadDemo {
private volatile int n;
}
4.多執行緒案例—單例模型(餓漢模式和懶漢模式)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/259986.html
標籤:其他
