线程的死锁
产生死锁的必要条件
1. 互斥条件:一个资源一次只能被一个进程使用。
2. 请求与保持条件:一个进程因请求资源而阻塞的时候,对已获得的资源保持不放。
3. 不剥夺条件:进程以及获得资源,在未使用完成前,不能强行剥夺。
4. 循环等待条件:若干进程之间形成头尾相接的循环等待资源关系。
死锁的案例:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 
 | package demo.study.ThreadTest;
 public class DeadLock {
 public static void main(String[] args) {
 makeup g1=new makeup("灰姑凉",0);
 makeup g2=new makeup("白雪公主",1);
 g1.start();
 g2.start();
 }
 }
 class Lipstick {
 }
 class Mirror{
 }
 class makeup extends Thread{
 static Lipstick lipstick = new Lipstick();
 static Mirror mirror= new Mirror();
 int choice;
 makeup(String name,int choice){
 super(name);
 this.choice=choice;
 }
 @Override
 public void run() {
 if (choice==0) {
 synchronized (lipstick) {
 System.out.println(Thread.currentThread().getName() + "获得了口红的锁");
 try {
 
 Thread.sleep(1000);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 
 synchronized (mirror) {
 System.out.println(Thread.currentThread().getName() + "获得了镜子的锁");
 }
 }
 }else{
 synchronized (mirror) {
 System.out.println(Thread.currentThread().getName() + "获得了镜子的锁");
 try {
 Thread.sleep(2000);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 
 synchronized (lipstick) {
 System.out.println(Thread.currentThread().getName() + "获得了口红的锁");
 }
 }
 }
 }
 }
 
 | 
由两个线程都抱着对方的锁不放,导致的死锁。
     
    
    
    
    
    
        
        
    
        -------------本文结束感谢您的阅读-------------