• 多线程锁


    public class TestThread6 {
        public static void main(String[] args) throws InterruptedException {
            MyClass mo = new MyClass();
            Prooess p = new Prooess(mo);//同一个对象
    
            Thread t1 = new Thread(p);
            t1.setName("t1");
            Thread t2 = new Thread(p);
            t2.setName("t2");
    
            //启动线程
            t1.start();
            Thread.sleep(3000);
            t2.start();
        }
    }
    class Prooess implements Runnable{
        MyClass mo ;
        public Prooess(MyClass mo){
            this.mo = mo;
        }
        @Override
        public void run() {
            if(Thread.currentThread().getName().equals("t1")) {
                mo.m1();
            }
            if(Thread.currentThread().getName().equals("t2")){
                mo.m2();
             }
        }
    
    }
    
    
    class MyClass{
        public synchronized void m1(){
            //休眠
            try{
                Thread.sleep(10000);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("m1");
        }
    //    public void m2(){//这里没有加锁  不需要等m1执行完直接输出
    ////        System.out.println("m2");
    ////    }
        public synchronized   void m2(){//同一把锁
            System.out.println("m2");
        }
    
    }
  • 相关阅读:
    文字转语音功能
    windows定时计划任务
    写电子合同,爬过的坑,趟过的雷,犯过的错,都是泪
    前端应该如何去认识http
    I/O理解
    观察者模式
    js --代理模式
    js --策略模式
    js --单例模式
    js 单线程 异步
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12417856.html
Copyright © 2020-2023  润新知