javaSE21/10/7

多线程

死锁

  • 多个线程互相持有对方需要的资源,然后形成僵持
public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup(0,"莉莉");
        Makeup makeup1 = new Makeup(1,"红红");
        makeup.start();
        makeup1.start();
    }

}
class Lipstick{//口红
}
class Mirror{//镜子
}
class Makeup extends Thread{
    //需要的资源只有一份,用static保证
    static Lipstick l = new Lipstick();
    static Mirror m = new Mirror();
    int choice;
    String girlNmae;
    public Makeup(int choice,String girlNmae){
        this.choice=choice;
        this.girlNmae=girlNmae;
    }
    @Override
    public void run() {
        makeUp();
    }
    private void makeUp(){
        //化妆:互相持有对方的锁,即需要拿到对方的资源
        if (choice==0){
            synchronized (l){//获得口红的锁
                System.out.println(this.girlNmae+"获得口红的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            //一个对象先将拿到的锁释放再拿别的对象的锁,就不会出现死锁
            synchronized (m){//一秒后再获得镜子的锁
                System.out.println(this.girlNmae+"获得镜子的锁");
            }
        }else{
            synchronized (m){//获得镜子的锁
                System.out.println(this.girlNmae+"获得镜子的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            //一个对象先将拿到的锁释放再拿别的对象的锁,就不会出现死锁
            }
            synchronized (l){//一秒后获得口红的锁
                System.out.println(this.girlNmae+"获得口红的锁");
            }
        }
    }
}

Lock

  • 更强大的线程同步机制——通过显示定义同步锁随想来实现同步。用Lock对象
上一篇:java语言手写高synchronized同步器锁和红黑树 以及对volatile关键字的底层分析(未完待续。。。)


下一篇:iOS 几种常用锁介绍