类锁与对象锁的研究

2019-01-28  本文已影响0人  天冷请穿衣

静态方法和非静态方法执行同步(synchronized)时,需要获取到一把锁。为了容易区分,我们分别称为类锁和对象锁。同步的实质是要获取到一个对象的锁,而每个类在JVM里都对应着一个对象,所以类锁也是一个对象锁。因此静态方法的锁和非静态方法的锁是不同的两把锁。

/*示例代码*/
public class TestSync {
    private static int num = 1000;
    
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            Sych.sync();

        });
        
        Thread t2 = new Thread(()->{
            Sych sych = new Sych();
            sych.notsync();
        });
        t1.start();
        t2.start();
    }
    public static class Sych{
        public synchronized void notsync() {
            for(int i = 0;i < 100; i ++) {
                num --;
                System.out.println(num);
                try {
                    Thread.sleep(20);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        public synchronized static void sync() {
            for(int i=0; i < 100; i ++) {
                num --;
                System.out.println(num);
                try {
                    Thread.sleep(20);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

运行的结果出现:

999
998
997
997
996
996
995
 ...

出现并发现象,说明静态方法和非静态方法的锁不是同一个锁。

上一篇 下一篇

猜你喜欢

热点阅读