java中静态方法中对象锁和类锁的区别和使用

java中一个重要的知识点就是线程锁机制,为了避免数据脏读,实现同步和异步,然后类中含有静态方法的同步和非静态方法的同步有什么区别呢?下面用代码来证实一把:

class service {
    
    public synchronized void printA(){
        
        Thread.sleep(5000);
        
        System.out.print("a");
        
    }
    
    public synchronized static  void printB(){
        System.out.print("b");
    }
    
    
}

//线程A

class ThreadA extends Thread{
    Service service;
    public ThreadA( Service service ){
        this.service = service;
    }
    public void run()  {  
         service.printA();
    }  
    
}

//线程B

class ThreadB extends Thread{
    Service service;
    public ThreadB( Service service ){
        this.service = service;
    }
    public void run()  {  
         service.printB();
    }  
    
}

//运行查看结果

class Run{
    
   
    public static void main(String[] args)  
    {  
    
        Service service = new Service();  
        ThreadA threadA = new ThreadA(service);  
        threadA.start(); 
        ThreadB threadB = new ThreadB(service);  
        threadB.start();  
    }  
    
}

结果: b a

分析:为什么没有同步输出?a结果的锁是类,他静态方法也是类方法,b结果锁是对象,不是同一个锁,所以结果输出是异步执行。