# Multi-thread note Base concept Thread ![](https://i.imgur.com/lQX2ijO.png) 1. Synchorized 在 static method 中 synchorized 是 lock A.class 也就是 ```Class<A>```. ``` class A { public synchorized static void k() { } } ``` 如果不是 static method 此時 lock 是 A 的 instance. ``` class A { public synchorized void k() { } } ``` 2. Volatile # Java Thread ``` Java public class VolatileExample { private static boolean running = false; private static Integer a = new Integer(10); public static void main(String[] argu) throws Exception { new Thread(new Runnable() { @Override public void run() { while (!running) { } System.out.println("Started."); while (running) { } System.out.println("Stopped."); } }).start(); Thread.sleep(1000); System.out.println("Thread Start"); running = true; Thread.sleep(1000); System.out.println("Thread Stop"); running = false; } } Result: Thread Start Thread Stop ``` Thread 居然沒有 stop!!! 請看此圖,CORE 1 負責 main thread , CORE 2 負責 thread 2,當 Thread 需要某個參數時,會從 L3 把值複製到 自己的 L1 或 L2,此時修改 running(true false) 變數只會修改到 自己的 L1 或 L2,可能幾個週期後才會把值寫入 L3,造成其他的 Thread 無法馬上讀到修改後的值,這時如果加入關鍵字 volatile,則會強制要讀取或修改值的 Thread 每項操作一定要經過 L3。 Volatile 用在 singleton 則是強制一定要一次 create 完 object 之後,一次寫入 L3。讀取也是強制一定要在 L3 讀取。 ![](https://i.imgur.com/SkhwgSI.png) 3. Lock 推薦使用 ReentrantLock,static 變數要搭配 volatile 去使用. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html 4. LockSupport 此東西會 block 著當前的 thread,只到有另一條 thread 呼叫 LockSupport.unpark. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/LockSupport.html ![](https://i.imgur.com/IrALMsh.png) ![](https://i.imgur.com/idKEv1M.png) 5. Object wait https://www.runoob.com/java/java-object-wait.html 6. Atomic ABA 問題 : https://blog.csdn.net/u012988901/article/details/112813473 Atomic 可以用於 App 在 foreground 與 background 狀態的判斷. 延伸 CAS, Compare And Swap