死锁:多个线程互相抱着对方需要的资源,然后形成僵持。
对于自己已有的资源不愿意放手。
package com.yf.syn;
public class DeadLock {
public static void main(String[] args) throws InterruptedException {
MakeUp g1 = new MakeUp(0,"yf1");
MakeUp g2 = new MakeUp(1,"yf2");
g1.start();
// Thread.sleep(2000);
g2.start();
}
}
//口红
class LipStick{
}
//镜子
class Mirror{
}
class MakeUp extends Thread{
//static保证资源只有一份
private static Mirror mirror = new Mirror();
private static LipStick lipStick = new LipStick();
private int choice;
private String name;
public MakeUp(int choice,String name){
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void makeup() throws InterruptedException {
if(choice == 0){
synchronized (mirror){
System.out.println(this.name+"拿到了镜子");
// sleep(2000);
synchronized (lipStick){
System.out.println(this.name+"拿到了口红");
}
}
}else{
synchronized (lipStick){
System.out.println(this.name+"拿到了口红");
// sleep(2000);
synchronized (mirror){
System.out.println(this.name+"拿到了镜子");
}
}
}
}
}
上述代码的情况就有可能会锁住,因为线程在拿到一个资源的基础上再想要去拿另外一个资源。
解决办法:要拿另外的资源,先把手里的资源给释放掉。
package com.yf.syn;
public class DeadLock {
public static void main(String[] args) throws InterruptedException {
MakeUp g1 = new MakeUp(0,"yf1");
MakeUp g2 = new MakeUp(1,"yf2");
g1.start();
// Thread.sleep(2000);
g2.start();
}
}
//口红
class LipStick{
}
//镜子
class Mirror{
}
class MakeUp extends Thread{
//static保证资源只有一份
private static Mirror mirror = new Mirror();
private static LipStick lipStick = new LipStick();
private int choice;
private String name;
public MakeUp(int choice,String name){
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void makeup() throws InterruptedException {
if(choice == 0){
synchronized (mirror){
System.out.println(this.name+"拿到了镜子");
// sleep(2000);
}
synchronized (lipStick){
System.out.println(this.name+"拿到了口红");
}
}else{
synchronized (lipStick){
System.out.println(this.name+"拿到了口红");
// sleep(2000);
}
synchronized (mirror){
System.out.println(this.name+"拿到了镜子");
}
}
}
}
产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个线程使用
- 请求与保持:一个线程因请求资源而阻塞时,对已有资源保持不放
- 不剥夺条件:线程已经获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:线程之前形成一种头尾相接的循环等待资源关系