1、定義
- Java 關鍵字
2、作用
- 同步方法/代碼塊,保證同一時刻只有 1 個線程執行。
3、特點
- 保證原子性:操作全部執行,或全部不執行。
- 保證可見性:一個線程修改共享屬性的值,其它線程能看到值的更改。JVM 內存空間:主存、工作內存。共享屬性修改流程:主存讀取,複製到工作內存,在工作內存修改,同步到主存。
- 保證有序性:單線程和多線,運行順序的結果一致。
4、原理
- 底層通過監視器對象(monitor)完成,wait()、notify() 方法依賴 monitor 對象。
- 監視器鎖(monitor)本質依賴於底層操作系統的互斥鎖實現。
4、具體使用
public class SynchronizedDemo {
public static void main(String[] args) {
MyThread thread1 = new MyThread("線程一");
MyThread thread2 = new MyThread("線程二");
thread1.start();
thread2.start();
}
public synchronized void method1() {
System.out.println("對象鎖:方法");
}
public void method2() {
synchronized (this) {
System.out.println("對象鎖:代碼塊");
}
}
public static synchronized void method3() {
System.out.println("類鎖:方法");
}
public void method4() {
synchronized (SynchronizedDemo.class) {
System.out.println("類鎖:代碼塊");
}
}
static class MyThread extends Thread {
// 100 張票
private static int ticket = 100;
public MyThread() {
super();
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
while (true) {
synchronized (MyThread.class) {
if (ticket > 0) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket--;
System.out.println(Thread.currentThread() + "賣掉了1張票,剩餘票數爲:" + ticket);
} else {
break;
}
}
}
}
}
}