1.三個執行緒同時搶票導致執行緒不安全
不安全的代碼
//測驗Lock鎖
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鎖
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
if (ticketNums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} else break;
}
}
}
三個執行緒同時訪問票,容易出現執行緒安全問題
運行結果

2.加上Lock鎖后
代碼
import java.util.concurrent.locks.ReentrantLock;
//測驗Lock鎖
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鎖
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
//加鎖
lock.lock();
if (ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}
else break;
}finally {
//解鎖
lock.unlock();
}
}
}
}
運行結果

3.Lock鎖與synchronized的對比
- lock是顯示鎖(手動開啟和關閉鎖,別忘記關閉鎖),synchronized是隱式鎖,出了作用域自動釋放
- lock只有代碼塊鎖,synchronized有代碼塊鎖和方法鎖
- 使用lock鎖,JVM將花費較少的時間來調度執行緒(性能更好)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/231100.html
標籤:其他
