死锁
-
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有“两个以上对象的锁”,就可能发生“死锁的问题”
-
举例化妆,只有同时拥有镜子和口红的锁才能开始化妆
package edu.wzw.TestUnsafe;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
MakeUp girl1=new MakeUp(1);
MakeUp girl2=new MakeUp(2);
new Thread(girl1,"灰姑娘").start();
new Thread(girl2,"白姑娘").start();
}
}
class Mirror{}//镜子
class Lipstick{}//口红
class MakeUp implements Runnable{
private int choice;//选择
//需要的资源只有一份,用static来保证只有一份
static Mirror mirror=new Mirror();
static Lipstick lipstick=new Lipstick();
public MakeUp(int choice){
this.choice=choice;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void makeup() throws InterruptedException {
if (choice==1){
synchronized (mirror){//获得口红的锁
System.out.println(Thread.currentThread().getName()+"拿到了口红的锁");
Thread.sleep(1000);
synchronized (lipstick){//一秒之后想要获得镜子的锁
System.out.println(Thread.currentThread().getName()+"拿到了镜子的锁");
}
}
}else{
synchronized (lipstick){//获得镜子的锁
System.out.println(Thread.currentThread().getName()+"拿到了镜子的锁");
Thread.sleep(2000);
synchronized (mirror){//一秒之后想要获得口红的锁
System.out.println(Thread.currentThread().getName()+"拿到了口红的锁");
}
}
}
}
}
这里死锁的解决办法,本来是拿了口红后再去拿镜子,改了之后变成:拿了口红之后放回去释放资源,然后再去拿镜子就不会造成死锁
锁中锁导致出现了两个以上对象的锁,额庵后都锁着不放,就造成死锁
package edu.wzw.TestUnsafe;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
MakeUp girl1=new MakeUp(1);
MakeUp girl2=new MakeUp(2);
new Thread(girl1,"灰姑娘").start();
new Thread(girl2,"白姑娘").start();
}
}
class Mirror{}//镜子
class Lipstick{}//口红
class MakeUp implements Runnable{
private int choice;//选择
//需要的资源只有一份,用static来保证只有一份
static Mirror mirror=new Mirror();
static Lipstick lipstick=new Lipstick();
public MakeUp(int choice){
this.choice=choice;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void makeup() throws InterruptedException {
if (choice==1){
synchronized (mirror){//获得口红的锁
System.out.println(Thread.currentThread().getName()+"拿到了口红的锁");
Thread.sleep(1000);
}synchronized (lipstick){//一秒之后想要获得镜子的锁
System.out.println(Thread.currentThread().getName()+"拿到了镜子的锁");
}
}else{
synchronized (lipstick){//获得镜子的锁
System.out.println(Thread.currentThread().getName()+"拿到了镜子的锁");
Thread.sleep(2000);
}synchronized (mirror){//一秒之后想要获得口红的锁
System.out.println(Thread.currentThread().getName()+"拿到了口红的锁");
}
}
}
}
死锁避免方法
-
产生死锁的四个必要条件
- 互斥条件:一个资源一次只能被一个资源使用
- 请求与保持条件:一个线程因请求资源而阻塞时,对已获得资源保持不放
- 不剥夺条件:线程已获得的资源,在未使用之前,不能强行剥夺
- 循环等待条件:若干线程之间形成一种头尾相接的循环等待资源关系
-
避免方法自行参悟,ok?