synchronized物件鎖和全域性鎖
阿新 • • 發佈:2020-12-18
技術標籤:java學習
public class A {
public synchronized void test() {
System.out.println("test開始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test結束..");
}
}
class MyThread extends Thread {
public void run() {
A a= new A();
a.test();
}
}
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
Thread thread = new MyThread();
thread.start();
}
}
物件鎖的效果
public synchronized void test() {
System.out.println ("test開始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test結束..");
}
public void test() {
synchronized (this) {
System.out.println("test開始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test結束..");
}
全域性鎖的效果:
每個執行緒new一個A物件,怎麼才能讓test方法不會同時被多執行緒執行。
解決也很簡單,只要鎖住同一個物件不就行了。例如,synchronized後的括號中鎖同一個固定物件,這樣就行了。這樣是沒問題,但是,比較多的做法是讓synchronized鎖這個類對應的Class物件。
- synchronized(A.class)實現了全域性鎖的效果。
public void test() {
synchronized (A.class) {
System.out.println("test開始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test結束..");
}
- static synchronized方法,static方法可以直接類名加方法名呼叫,方法中無法使用this,所以它鎖的不是this,而是類的Class物件,所以,static synchronized方法也相當於全域性鎖,相當於鎖住了程式碼段。
public static synchronized void test() {
System.out.println("test開始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test結束..");
}