java并发编程学习之一段简单代码证明synchronized锁的是对象

废话不多说,上代码!

public class Thread9 {
  public static void main(String[] args) {
      Thread9_Util t9 = new Thread9_Util();
      Thread9_1 t91 = new Thread9_1(t9);
      Thread9_2 t92 = new Thread9_2(t9);
      t91.start();
      t92.start();
}
}
class Thread9_1 extends Thread{
    private Thread9_Util thread9_Util ;
    public Thread9_1(Thread9_Util t9){
        this.thread9_Util= t9;
    }
    @Override
    public void run() {
        thread9_Util.print1(Thread.currentThread().getId());
        System.out.println(Thread.currentThread().getId()+"  end");
    }
}
class Thread9_2 extends Thread{
    private Thread9_Util thread9_Util ;
    public Thread9_2(Thread9_Util t9){
        this.thread9_Util= t9;
    }
    @Override
    public void run() {
            thread9_Util.print2(Thread.currentThread().getId());
        System.out.println(Thread.currentThread().getId()+"  end");

    }
}
class Thread9_Util {
   synchronized void print1(long l){
        System.out.println(l);
       try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
   synchronized void print2(long l){
        System.out.println(l);
       try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }

}

打印结果:
10
//有延迟
9
10 end
//有延迟
9 end

当然,如果去掉print2中的synchronized方法,打印10和9 的时候是没有延迟时间的,说明,非同步的方法还是能够被其他线程继续访问的。

猜你喜欢

转载自blog.csdn.net/iphone4grf/article/details/50374313