zoukankan      html  css  js  c++  java
  • java模拟死锁

    使用synchronized 关键字,两个线程分别占用两个string,然后sleep,两个线程分别请求对方string、形成死锁

    package learning;
    
    import java.util.Date;
    
    class LockA extends Thread{
        public void run(){
            try{
                System.out.println(new Date().toString()+"Lock A 开始执行");
                while(true){
                    synchronized (LockTest.obj1){
                        System.out.println(new Date().toString()+"Lock A 锁住 obj1");
                        Thread.sleep(3000);
                        synchronized (LockTest.obj2){
                            System.out.println(new Date().toString()+"Lock A 锁住 obj2");
                            Thread.sleep(60*1000);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
    
    }
    class LockB extends Thread{
        public void run(){
            try{
                System.out.println(new Date().toString()+"Lock B 开始执行");
                while(true){
                    synchronized (LockTest.obj2){
                        System.out.println(new Date().toString()+"Lock B 锁住 obj2");
                        Thread.sleep(3000);
                        synchronized (LockTest.obj1){
                            System.out.println(new Date().toString()+"Lock B 锁住 obj1");
                            Thread.sleep(60*1000);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
    
    }
    class LockTest{
        public static String obj1="obj1";
        public static String obj2="obj2";
        public static void main(String []arg){
            LockA lockA=new LockA();
            lockA.start();
            LockB lockB=new LockB();
            lockB.start();
    
        }
    }
  • 相关阅读:
    Python 字符串操作
    Python 字典操作
    16 飞机大战:思路整理、重要代码
    15 飞机大战:pygame入门、python基础串连
    14 windows下安装pygame模块
    13 制作模块压缩包、安装模块
    12 包及导包
    11 模块、模块的搜索顺序、__file__内置属性、__name__属性
    异常集
    10 异常
  • 原文地址:https://www.cnblogs.com/jieyi/p/13441026.html
Copyright © 2011-2022 走看看