0
点赞
收藏
分享

微信扫一扫

偏向锁批量撤销代码

诗尚凝寒 2022-04-14 阅读 46
java
public class LockFlate {

    public static void main(String[] args) throws Exception {
        Thread.sleep(5000);
        List<A> listA = new ArrayList<>();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i <100 ; i++) {
                A a = new A();
                synchronized (a){
                    listA.add(a);
                }
            }

        });
        t1.start();
        Thread.sleep(3000);

        Thread t2 = new Thread(() -> {
            //这里循环了40次。达到了批量撤销的阈值
            for (int i = 0; i < 60; i++) {
                A a =listA.get(i);
                synchronized (a){
                    out.print("");
                }
            }
        });
        t2.start();
        Thread.sleep(3000);

        Thread t3 = new Thread(() -> {
            //这里循环了40次。达到了批量撤销的阈值
            for (int i = 20; i < 60; i++) {
                A a =listA.get(i);
                synchronized (a){
                    out.print("");
                }
            }
        });
        t3.start();
        Thread.sleep(3000);

        /*
            前后输出结果不一致。
            如果先执行这段,则偏向锁不撤销。
            如果这段放到后面执行,偏向锁批量撤销
        out.println((ClassLayout.parseInstance(listA.get(99)).toPrintable()));
        synchronized (listA.get(99)){
            out.println((ClassLayout.parseInstance(listA.get(99)).toPrintable()));
        }*/


        out.println("重新输出新实例A");
        out.println((ClassLayout.parseInstance(new A()).toPrintable()));

        out.println((ClassLayout.parseInstance(listA.get(99)).toPrintable()));
        synchronized (listA.get(99)){
            out.println((ClassLayout.parseInstance(listA.get(99)).toPrintable()));
        }

    }
}
class A{

}
举报

相关推荐

0 条评论