synchronized

synchrnized是可以重入的,但是只允许已经拥有锁的线程重新获得锁,以下写了一个测试代码证实了一件事那就是

一道常用的面试题:

当一个线程进入了一个对象的synchronized修饰的方法A,那么另外一个线程不能进入这个对象的synchronized修饰的方法B

因为synchronized是锁对象的.

public class learnSynchronized {
    public synchronized void method1() throws Exception{
        System.out.println("method1");
            method2();
    }

    public synchronized void method2() throws Exception{
        System.out.println("method2");
        Thread.sleep(5000);
    }

    public synchronized void method3(){
        System.out.println("method3");
    }
    public static void main(String[] args) throws Exception{
        final learnSynchronized learnsynchr=new learnSynchronized();
        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run()  {
                try {
                    learnsynchr.method1();
                }
                catch (Exception e){
                    System.out.println(e.toString());
                }
            }
        });
        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                learnsynchr.method3();
            }
        });

        thread1.start();

        thread2.start();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值