死锁
通俗理解
现在有两个东西,一个是汽车,一个是火车,小明已经拿上汽车了,但是他想要火车,
小红已经有火车了,但是他想要汽车,等在等对方放手之后,就可以拿到自己想要的,
但是谁也不想要第一个放开,所以都在等对方放开,就出现了僵持的情况
Lock 锁
Lock 就是一个接口
多个线程操作同一个资源(线程不安全)代码
买票的例子
public class shiLock {
public static void main(String[] args) {
mp mp = new mp();
new Thread(mp).start();
new Thread(mp).start();
new Thread(mp).start();
}
}
class mp implements Runnable{
private int ticket =10;
@Override
public void run() {
while (true){
if (ticket<=0){
break;
}else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticket--);
}
}
}
}
以前我们是使用synchronized 关键字进行线程安全的。
使用 Lock 锁
使用 Lock 锁 进行 买票
public class shiLock {
public static void main(String[] args) {
mp mp = new mp();
new Thread(mp).start();
new Thread(mp).start();
new Thread(mp).start();
}
}
class mp implements Runnable{
private int ticket =10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
if (ticket<=0){
break;
}else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticket--);
}
}finally {
lock.unlock();
}
}
}
}
首先创建一个lock锁
private final ReentrantLock lock = new ReentrantLock();
加锁 解锁
lock.lock();
lock.unlock();