java线程之Lock锁,三个线程抢票加上lock锁后变成三个线程排队买票
程序员文章站
2024-01-20 16:09:52
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(testloc...
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){
//加锁
lock.lock();
try {
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://blog.csdn.net/qq_45895576/article/details/110731986