zoukankan      html  css  js  c++  java
  • Java多线程学习——死锁的一个容易理解的例子

    发生死锁的情况:多个线程需要同时占用多个共享资源而发生需要互相死循环等待的情况

    public class Mirror {   //镜子
    }
    public class Lipstick { //口红
    }

    线程类

    public class Makeup implements Runnable{
        static private Lipstick lipstick=new Lipstick();    //口红
        static private Mirror mirror=new Mirror();  //镜子
        private int choice; //0代表先拿口红,1代表先拿镜子mm
        private String name;
    
        public Makeup(int choice,String name) {
            this.choice = choice;
            this.name=name;
        }
    
        @Override
        public void run() {
            makeup();
        }
        public void makeup(){
            if(choice==0){
                synchronized (lipstick){
                    System.out.println(name+"涂口红");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (mirror){
                        System.out.println(name+"照镜子");
                    }
                }
            }else{
                synchronized (mirror){
                    System.out.println(name+"照镜子");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lipstick){
                        System.out.println(name+"涂口红");
                    }
                }
            }
        }
    }
    public class TestMakeup {
        public static void main(String[] args) {
            new Thread(new Makeup(0,"张柏芝")).start();
            new Thread(new Makeup(1,"王菲")).start();
        }
    }

    解决方案:

    将嵌套的同步机制改为“顺序”的同步机制,即我不需要同时占有,这里只是一个例子

    if(choice==0){
                synchronized (lipstick){
                    System.out.println(name+"涂口红");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                synchronized (mirror){
                    System.out.println(name+"照镜子");
                }
            }
  • 相关阅读:
    linux资源监控命令详解
    c语言入门教程 / c语言入门经典书籍
    Hive存储过程实现-hpsql
    Hive集成mysql数据库
    Hive安装与配置
    Hbase shell操作总结(2)
    Hbase shell操作总结(1)
    Hbase 原理介绍
    Hbase的安装与配置
    Zookeeper工作原理(详细)
  • 原文地址:https://www.cnblogs.com/chiweiming/p/11149485.html
Copyright © 2011-2022 走看看