
死锁

形成死锁的条件
public class TestDeadLock extends Thread {
//需要的资源用static保证只有一份
private static Rice rice = new Rice();
private static Water water = new Water();
private int choice;
private String name;
public TestDeadLock(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
live();
}
//互相持有对方需要的资源的锁,需要拿到对方的资源
public void live(){
if (choice == 0) {
synchronized (rice) { //获得米饭的锁
try {
System.out.println(this.name + "获得米饭的锁");
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (water) { //1秒后想获得水的锁
System.out.println(this.name + "获得水的锁");
}
}
} else {
synchronized (water) { //获得水的锁
try {
System.out.println(this.name + "获得水的锁");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (rice) { //1秒后想获得米饭的锁
System.out.println(this.name + "获得米饭的锁");
}
}
}
}
public static void main(String[] args) {
TestDeadLock people1 = new TestDeadLock(0, "张三");
TestDeadLock people2 = new TestDeadLock(1, "李四");
people1.start();
people2.start();
}
}
class Rice {
}
class Water {
}
运行结果:

运行结果
程序卡在这里
避免死锁:
public void live(){
if (choice == 0) {
synchronized (rice) { //获得米饭的锁
try {
System.out.println(this.name + "获得米饭的锁");
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (water) { //1秒后想获得水的锁
System.out.println(this.name + "获得水的锁");
}
} else {
synchronized (water) { //获得水的锁
try {
System.out.println(this.name + "获得水的锁");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (rice) { //1秒后想获得米饭的锁
System.out.println(this.name + "获得米饭的锁");
}
}
}
先获得一个资源的锁。然后释放,然后再去获得另一个资源的锁。