繁体   English   中英

需要代码来理解同步的 static 和同一实例上的两个不同线程同时访问的非静态方法

[英]Need code to understand synchronized static and non-static methods being accessed at the same time by two different threads on the same instance

class A
{
    synchronized static void m1()
    {
        System.out.println("In m1 A");
    }
    synchronized void m2()
    {
        System.out.println("In m2 A");
    }
}

有两个线程 T1 和 T2。 T1 正在访问 m1 方法。 T2 能否同时访问同一实例上的 m2 方法?

上面的段落和代码是在学习资源上提出的问题。 答案是“是的,两个线程可以访问两种方法,一个是 static 同步,另一个是在同一实例上同时进行非静态同步”。

我想借助一个小代码片段来理解这一点,但无法编写一个。 你能帮帮我吗?

PS:我找到了我正在寻找的答案。 一个问题是如何使用实例调用 static 方法。 我的回答中也提到了这一点。 感谢那些在没有发表居高临下的言论的情况下发表评论的人。

我找到了我要找的东西,如果我错了,请纠正我

public class ObjecAndClassLevelLock
{
    public static void main(String[] args)
    {
        ThreadExample te=new ThreadExample();

        Thread t1= new Thread(() -> te.m1());
        Thread t2=new Thread(()->ThreadExample.m2());
        t1.start();
        t2.start();

    }
}


class ThreadExample extends Thread
{
    public synchronized void m1(){
        System.out.println(Thread.currentThread().getName());
        System.out.println("Sync Method");
    }
    public static synchronized void m2(){
        System.out.println(Thread.currentThread().getName());
        System.out.println("Static Sync Method");
    }
}
 final ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(()->{
            A a = new A();
            for(int i = 0; i < 10000; i++)
                a.m2();
        });

        for(int i = 0; i < 10000; i++)
            A.m1();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM