java - 调用同步方法时线程调用非同步实例方法

标签 java multithreading synchronization thread-safety

public class Common {      
    public synchronized void synchronizedMethod1() {
        System.out.println("synchronizedMethod1 called");
        try {
            Thread.sleep(1000);
            } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("synchronizedMethod1 done");
    }
    public void method1() {
        System.out.println("Method 1 called");
        try {
            Thread.sleep(1000);
            } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 1 done");
    }
}



public class MyThread extends Thread {
    private int id = 0;
    private Common common;

    public MyThread(String name, int no, Common object) {
        super(name);
        common = object;
        id = no;
    }

    public void run() {
        System.out.println("Running Thread" + this.getName());
        try {
            if (id == 0) {
                common.synchronizedMethod1();
                } else {
                common.method1();
            }
            } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Common c = new Common();
        MyThread t1 = new MyThread("MyThread-1", 0, c);
        MyThread t2 = new MyThread("MyThread-2", 1, c);
        t1.start();
        t2.start();
    }
}

输出:

Running ThreadMyThread-1  
synchronizedMethod1 called  
Running ThreadMyThread-2  
Method 1 called  
synchronizedMethod1 done  
Method 1 done  

我想找到一种方法来阻止method1()在我调用synchronizedMethod1时运行。除非我弄错了,否则所有方法都会被调用,并且 Java 会在运行时期间和之前编译它们,无论它是否同步。

我应该使用 Lock 对象来代替和/或不让 method1() 成为同步方法吗?

最佳答案

I would like to find a way to prevent method1() from running when i called synchronizedMethod1

最简单的方法是使 method1()同步。这意味着这两种方法都会导致对它们正在调用的 Common 实例进行锁定。只有一个线程能够调用 synchronizedMethod1()method1()

Unless I'm mistaken all methods are called and Java compiles them during and before runtime regardless if it's synchronized or not.

我不明白这个问题。您确实不必担心 JVM 的编译或优化阶段。

Should i have used a Lock object instead?

通常认为使方法同步不如使用私有(private)最终锁定对象。锁定对象只是让您的锁定更加细粒度。例如,通过方法锁定,日志消息和其他不需要保护的语句也将被同步。但如果目标是锁定整个方法,那么同步方法就可以了。

关于java - 调用同步方法时线程调用非同步实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549383/

相关文章:

java - Future中的get方法在java中是如何工作的?

java - 将不同类型的对象存储在一个数组中,形成对象数组

java - Android 为实用方法编写单元测试

multithreading - IORef 和 MVar 有什么区别?

c++ - 实现线程监控机制所需的帮助

go - 如何在不使用 time.Sleep 的情况下等待所有 goroutines 完成?

java - 同步块(synchronized block)不会锁定

java - 如何在 AWS Java SDK v2 Apache 客户端上设置代理

java - java 的内存值

c# - .NET 线程与操作系统线程不同吗?