• java多线程_类锁的使用


    /*
        类锁,类只有一个,所以锁是类级别的,只有一个.
    */
    public class ThreadTest17
    {
        public static void main(String[] args) throws Exception{
            
            Thread t1 = new Thread(new Processor());
            Thread t2 = new Thread(new Processor());
    
            t1.setName("t1");
            t2.setName("t2");
    
            t1.start();
            
            //延迟,保证t1先执行
            Thread.sleep(1000);
    
            t2.start();
    
        }
    }
    
    class Processor implements Runnable
    {
        public void run(){
            
            if("t1".equals(Thread.currentThread().getName())){
                MyClass.m1();
            }
    
            if("t2".equals(Thread.currentThread().getName())){
                MyClass.m2();
            }
        }
    }
    
    class MyClass
    {
        //synchronized添加到静态方法上,线程执行此方法的时候会找类锁。
        public synchronized static void m1(){
            
            try{Thread.sleep(10000);}catch(Exception e){}
    
            System.out.println("m1....");
        }
    
        //m2方法等m1结束之后才能执行,该方法有synchronized
        //线程执行该代码需要“类锁”,而类锁只有一个。类锁锁定的是该类对应的Class对象
        public synchronized static void m2(){
            System.out.println("m2...");
        }
    }
  • 相关阅读:
    C he 指针
    typedef 与 define
    (转)ubuntu中安装man手册查看函数原型
    .9 赫夫曼编码
    .8 AVL树
    PowerDesigner使用技巧
    C#基础
    NET框架设计
    Sql Server 执行计划及Sql查询优化
    SQL SERVER函数浅析
  • 原文地址:https://www.cnblogs.com/Allen-win/p/7352533.html
Copyright © 2020-2023  润新知