• synchronized 修饰在 static方法和非static方法的区别


    Java中synchronized用在静态方法和非静态方法上面的区别

      在Java中,synchronized是用来表示同步的,我们可以synchronized来修饰一个方法。也可以synchronized来修饰方法里面的一个语句块。那么,在static方法和非static方法前面加synchronized到底有什么不同呢?大家都知道,static的方法属于类方法,它属于这个Class(注意:这里的Class不是指Class的某个具体对象),那么static获取到的锁,是属于类的锁。而非static方法获取到的锁,是属于当前对象的锁。所以,他们之间不会产生互斥。

      看代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    public class Demo {
        public static synchronized void staticFunction()
                throws InterruptedException {
            for (int i = 0; i < 3; i++) {
                Thread.sleep(1000);
                System.out.println("Static function running...");
            }
        }
     
        public synchronized void function() throws InterruptedException {
            for (int i = 0; i <3; i++) {
                Thread.sleep(1000);
                System.out.println("function running...");
            }
        }
     
        public static void main(String[] args) {
            final Demo demo = new Demo();
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        staticFunction();
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
     
            Thread thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        demo.function();
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
     
            thread1.start();
            thread2.start();
        }
    }

      运行结果是:

    1
    2
    3
    4
    5
    6
    function running...
    Static function running...
    function running...
    Static function running...
    function running...
    Static function running...

      那当我们想让所有这个类下面的方法都同步的时候,也就是让所有这个类下面的静态方法和非静态方法共用同一把锁的时候,我们如何办呢?此时我们可以使用Lock。

  • 相关阅读:
    Google新闻昨晚发生全球服务中断 波及国内 狼人:
    德国"反黑客"法出炉:拥有黑客工具是非法的 狼人:
    百付宝携手瑞星 打造零风险支付平台 狼人:
    四月新增电脑病毒180万 2千万台次电脑遭攻击 狼人:
    PDF文件和Word文档面临更多网络安全威胁 狼人:
    麻省理工学生令计算机系统升级不需重启 狼人:
    nullnullIOS控件AlertView的使用
    设置源ARM中断处理_S3C2440
    软件授权码Python之道Python连接MYSQL数据库和发送邮件
    目标文件符号《深入理解计算机系统》笔记(三)链接知识【附图】
  • 原文地址:https://www.cnblogs.com/toSeeMyDream/p/8194491.html
Copyright © 2020-2023  润新知