美文网首页
003--20200413学习

003--20200413学习

作者: 糖纸疯了 | 来源:发表于2020-04-14 01:36 被阅读0次

    1、导入对象头

        <!--查看对象头-->
        <dependency>
            <groupId>org.openjdk.jol</groupId>
            <artifactId>jol-core</artifactId>
            <version>0.9</version>
        </dependency>
    

    2、创建锁对象

    package com.enzoism.springboot.lock;
    
    /**
     * Created with IntelliJ IDEA.
     * User: enzoism
     * Date: 2020/4/14- 1:11
     */
    public class LockObject {
        private boolean flag;
        private int num;
    }
    

    3、进行锁对象和查看对象头


    package com.enzoism.springboot.lock;
    
    import org.openjdk.jol.info.ClassLayout;
    
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * Created with IntelliJ IDEA.
     * User: enzoism
     * Date: 2020/4/14- 1:11
     */
    public class TestLock {
    
        static ReentrantLock lock = new ReentrantLock();
        static LockObject lockObject = new LockObject();
    
        public static void main(String[] args) {
    //        testLock1();
    //        testLock2();
            testLockAnalysis();
    
        }
    
        public static void testLock1() {
            // 使用ReentrantLock进行加锁-JUC包
            lock.lock();
            System.out.println("11111");
            System.out.println("22222");
            lock.unlock();
        }
    
        public static void testLock2() {
            // 使用synchronized进行加锁-JDK原生
            synchronized (lockObject) {
                System.out.println("11111");
                System.out.println("22222");
            }
        }
    
        public static void testLockAnalysis() {
            // 查看对象头
            System.out.println(ClassLayout.parseInstance(lockObject).toPrintable());
        }
    }
    

    相关文章

      网友评论

          本文标题:003--20200413学习

          本文链接:https://www.haomeiwen.com/subject/rpsamhtx.html