javaSE21/10/7

2021/10/7 22:12:54

本文主要是介绍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对象


这篇关于javaSE21/10/7的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程