gpt4 book ai didi

Class Monitor 实战

转载 作者:知者 更新时间:2024-03-13 05:57:52 28 4
gpt4 key购买 nike

一 同一类的静态方法都用 synchronized 修饰

1 代码

package concurrent;

import java.util.concurrent.TimeUnit;

public class ClassMonitor {
    public static synchronized void method1() {
        System.out.println(Thread.currentThread().getName() + " enter to method1");
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " exit to method1");
    }

    public static synchronized void method2() {
        System.out.println(Thread.currentThread().getName() + " enter to method2");
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " exit to method2");
    }

    public static void main(String[] args) {
        ClassMonitor thisMonitor = new ClassMonitor();
        new Thread(ClassMonitor::method1, "T1").start();
        new Thread(ClassMonitor::method2, "T2").start();
    }
}

2 测试

T1 enter to method1

T1 exit to method1

T2 enter to method2

T2 exit to method2

二 同一类的静态方法分别用 synchronized 修饰和 synchronized 代码块修饰

1 代码

package concurrent;

import java.util.concurrent.TimeUnit;

public class ClassMonitor1 {
    public static synchronized void method1() {
        System.out.println(Thread.currentThread().getName() + " enter to method1");
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " exit to method1");
    }

    public static void method2() {
        synchronized (ClassMonitor1.class) {
            System.out.println(Thread.currentThread().getName() + " enter to method2");
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " exit to method2");
        }
    }

    public static void main(String[] args) {
        ClassMonitor1 thisMonitor = new ClassMonitor1();
        new Thread(ClassMonitor1::method1, "T1").start();
        new Thread(ClassMonitor1::method2, "T2").start();
    }
}

2 测试

T1 enter to method1

T1 exit to method1

T2 enter to method2

T2 exit to method2

三 结论

上面两组代码执行效果一样,在同一时刻只能有一个线程访问 ClassMonitor 的静态方法,用 synchronized 同步某个类的不同静态方法争抢的是同一 monitor 的 lock,与该 monitor 关联的引用是 ClassMonitor 实例。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com