什么是死锁
多个线程各种占有一些共享资源,并且互相等待其他线程占有资源才能运行,而导致两个或者多个线程都在等待对方是否资源,都停止执行的情况,某个同步块同时拥有“2个以上对象锁”的时候,就可能发生“死锁”的现象。
//死锁:多个对象互相拥有对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
DriveCar driveCar = new DriveCar(0,"职业老司机");
DriveCar driveCar2 = new DriveCar(1,"新手上路");
driveCar.start();
driveCar2.start();
}
}
//车钥匙
class CarKey{
}
//车
class Car{
}
class DriveCar extends Thread {
static CarKey carKey = new CarKey();
static Car car = new Car();
//选择
int changeGoods ;
//司机
String driver;
//构造函数,初始化。
public DriveCar(int changeGoods, String driver) {
this.changeGoods = changeGoods;
this.driver = driver;
}
@Override
public void run() {
//开车
try {
DriveCarMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开车,互相拥有对方的资源
private void DriveCarMethod() throws InterruptedException {
if(changeGoods == 0) {
synchronized (carKey){
System.out.println(driver+"我获得了车钥匙");
Thread.sleep(1000);
synchronized (car){
System.out.println(driver+"我可以开车了");
}
}
}else{
synchronized (car){
System.out.println(driver+"我获得了车");
Thread.sleep(2000);
synchronized (carKey){
System.out.println(driver+"我可以开车了");
}
}
}
}
}
解决死锁代码如下
public class DeadLock {
public static void main(String[] args) {
DriveCar driveCar = new DriveCar(0,"职业老司机");
DriveCar driveCar2 = new DriveCar(1,"新手上路");
driveCar.start();
driveCar2.start();
}
}
//车钥匙
class CarKey{
}
//车
class Car{
}
class DriveCar extends Thread {
static CarKey carKey = new CarKey();
static Car car = new Car();
//选择
int changeGoods ;
//司机
String driver;
//构造函数,初始化。
public DriveCar(int changeGoods, String driver) {
this.changeGoods = changeGoods;
this.driver = driver;
}
@Override
public void run() {
//开车
try {
DriveCarMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开车,互相拥有对方的资源
private void DriveCarMethod() throws InterruptedException {
if(changeGoods == 0) {
synchronized (carKey){
System.out.println(driver+"我获得了车钥匙");
}
synchronized (car){
System.out.println(driver+"我可以开车了");
}
}else{
synchronized (car){
System.out.println(driver+"我获得了车");
}
synchronized (carKey){
System.out.println(driver+"我可以开车了");
}
}
}
}
总结:参数死锁四个必要条件,只要想办法破坏其中任意一个或多个条件,就不免死锁的发生。
- 互斥条件,一个资源没错都只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而被阻塞时,对已获得的资源保持不放。
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
- 循环等待条件:若干进程之间形成一个头尾相接的循环等待资源关系