package gaoji;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
//定義lock鎖,ReentrantLock可重置鎖
private final ReentrantLock lock = new ReentrantLock();
synchronized 與 Lock的對比
-
Lock是顯示鎖(手動開啟和關閉鎖,別忘記關閉鎖)synchronized是隱式鎖,出了作用域自動釋放
-
Lock只有代碼塊鎖,synchronized有代碼塊鎖和方法鎖
-
使用Lock鎖,JVM將花費較少的時間來調度線程,性能更好,並且具有更好的擴展性(提供更多的子類)
-
優先使用順序:
Lock > 同步代碼塊(已經進入了方法體,分配了相應資源)>同步方法(在方法體之外)
-