一个类中有多个synchronized关键字修饰的方法调用顺序问题

class Exam1 {
	public synchronized void methodThree() {
        System.out.println("methodThree() begin:" + (new       SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format((new Date())));
        long i = 0L;
        while (i < 100000000000L) {
            i++;
        }
        System.out.println(i);
        System.out.println("methodThree() end:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format((new Date())));
    }

    public synchronized void methodFour() {
        System.out.println("methodFour() begin");
        System.out.println("methodFour() end");
    }
}
public class Exam2 {
     public static void main(String[] args) {
        final Exam1 exam1 = new Exam1();
   
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                exam1.methodThree();
            }

        });
        t3.start();

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                exam1.methodFour();
                timer.cancel();
            }
        }, 50, 10);
    }
}

代码如上所示,Exam1类有两个方法,methodThree( )和methodFour( ):
1、methodThree( )和methodFour( )都没有加synchronized关键字时,调用结果如下所示:

methodThree() begin:2019-05-01 21:22:45
methodFour() begin
methodFour() end
methodThree() end:2019-05-01 21:23:17

结论:调用methodThree( ),不影响methodFour( )的调用。
2、methodThree( )和methodFour( )都加synchronized关键字时,调用结果如下所示:

methodThree() begin:2019-05-01 21:36:28
methodThree() end:2019-05-01 21:37:00
methodFour() begin
methodFour() end

结论:必须按调用的顺序依次执行。
3、methodThree( )和methodFour( )只有其中一个加synchronized关键字时,调用结果如下所示:

methodThree() begin:2019-05-01 21:22:45
methodFour() begin
methodFour() end
methodThree() end:2019-05-01 21:23:17

结论:不加锁的那个方法不受影响。

static注意:
methodThree( )和methodFour( )都是static静态方法,且都加了synchronized关键字,创建不同的线程分别调用methodThree( )和methodFour( ),需要等methodThree( )执行完成才能执行methodFour( )(因为static方法是单实例的,methodThree( )持有的是Class锁,Class锁可以对类的所有对象实例起作用)

总结

同一个object中多个方法都加了synchronized关键字的时候,其中调用任意方法之后需等该方法执行完成才能调用其他方法,即同步的,阻塞的;synchronized(this)同步代码块的场景也是如此。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值