synchronized的其他用法

本文通过两个示例深入解析Java中同步方法的调用机制。首先,展示了一个类中多个同步方法的调用顺序,说明了它们如何保证线程安全。其次,探讨了父类与子类中synchronized关键字的使用,以及在多线程环境下如何影响实例变量的修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用法一、关于函数的调用

代码:

public class Thread2 {
    public synchronized void  method1(){
        System.out.println("method1..");
        method2();
    }
    public synchronized void  method2(){
        System.out.println("method2..");
        method3();
    }
    public synchronized void  method3(){
        System.out.println("method3..");
    }

    public static void main(String[] args) {
        final  Thread2  t2 = new Thread2();
        Thread thread = new Thread(() -> t2.method1());
        thread.start();
    }
}

执行结果:

cd95a00d8833f7f8340efd18ac0882e9bdf.jpg

用法二、关于父类,子类的synchronized用法

代码:

public class Thread3 {

    static class Main{
        public  int  i =10;
        public  synchronized  void operationSup(){
            try {
                i--;
                System.out.println("Main print i = "+i);
                Thread.sleep(100);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Sub extends  Main{
        public  synchronized void operationSub(){
            try {
                while (i>0){
                    i--;
                    System.out.println("Sub print i = "+i);
                    Thread.sleep(100);
                    this.operationSup();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
          Sub sub = new Sub();
          sub.operationSub();
        });
        t1.start();
    }
}

运行结果:

a9a4e89f3c9a893c552009e1e3180ee1a7d.jpg

 

注:初学者,写的不好请见谅,如有相关问题记得私信我

转载于:https://my.oschina.net/chenzhou/blog/2885333

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值