zoukankan      html  css  js  c++  java
  • 2.2.14内置类与同步:测试1

    本实验测试是在内置类中有两个同步方法,但使用的却是不同的锁,打印结果也是异步的

    package com.cky.bean;
    
    /**
     * Created by edison on 2017/12/9.
     */
    public class OutClass {
        static class Inner {
            public void method1(){
                synchronized ("其他的锁") {
                    for (int i = 0; i <= 10; i++) {
                        System.out.println(Thread.currentThread().getName() +" i="+i);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
    
            public synchronized  void method2() {
                for (int i = 11; i <=20 ; i++) {
                    System.out.println(Thread.currentThread().getName() + " i="+i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    package com.cky.bean;
    
    /**
     * Created by edison on 2017/12/9.
     */
    public class Test2 {
        public static void main(String[] args) {
            OutClass.Inner inner = new OutClass.Inner();
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    inner.method1();
                }
            }, "A");
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    inner.method2();
                }
            }, "B");
            t1.start();
            t2.start();
        }
    }
    B i=11
    A i=0
    B i=12
    A i=1
    B i=13
    A i=2
    B i=14
    A i=3
    B i=15
    A i=4
    B i=16

    由于持有不同的对象监视器,所以打印结果就是乱序的。

  • 相关阅读:
    Redis配置参数详解
    amoeba实现读写分离
    P1525 关押罪犯 并查集
    模板汇总——treap
    差分约束
    HDU
    CodeForces 522C Chicken or Fish?
    CodeForces 812E Sagheer and Apple Tree 树上nim
    CodeForces 855E Salazar Slytherin's Locket
    CodeForces 283C World Eater Brothers
  • 原文地址:https://www.cnblogs.com/edison20161121/p/8011182.html
Copyright © 2011-2022 走看看