java - 两个同步方法是否同时执行

标签 java multithreading synchronized

我在一个类中有 4 个方法(m1m2m3m4)。方法 m1m2m3synchronized 方法。另外,我分别有 4 个线程 t1t2t3t4

如果t1访问m1方法(同步方法),t2线程可以访问m2方法(同步方法)同时?如果不是,t2的状态是什么?

最佳答案

If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously?

synchronized关键字适用于对象级别,只有一个线程可以持有对象的锁。所以只要你说的是同一个对象,那么not2会等待t1释放进入时获取的锁m1.

但是,线程可以通过调用 Object.wait() 释放锁而无需从方法返回。

If not, what would be the state of t2 ?

它会紧紧地等待 t1 释放锁(从方法返回或调用 Object.wait())。具体来说,它将位于 BLOCKED state .

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

示例代码:

public class Test {

    public synchronized void m1() {
        try { Thread.sleep(2000); }
        catch (InterruptedException ie) {}
    }

    public synchronized void m2() {
        try { Thread.sleep(2000); }
        catch (InterruptedException ie) {}
    }

    public static void main(String[] args) throws InterruptedException {
        final Test t = new Test();
        Thread t1 = new Thread() { public void run() { t.m1(); } };
        Thread t2 = new Thread() { public void run() { t.m2(); } };

        t1.start();
        Thread.sleep(500);

        t2.start();
        Thread.sleep(500);

        System.out.println(t2.getState());
    }
}

输出:

BLOCKED

关于java - 两个同步方法是否同时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3160023/

相关文章:

java - 来自 xsd 的 JAXB 类(其中包含其他 xsd 导入)时出错

java - 准备语句因 DB2 SQL 错误而失败

java - 如何将 KML 发送到本地运行的 Google-Earth?

Python 应用程序级文档/记录锁定(例如,对于 MongoDB)

c# - 多线程时进度条不显示正确的值

java - 为什么在Java中在synchronized之前使用void关键字会抛出错误,但反过来却可以正常工作?

即使单击按钮多次,Javafx 也仅启动一个线程

c# - volatile 用法的可重现示例

java - 如何从非 Activity 类开始一个 Activity 并等到它完成?

java - ReentrantLock 是否足够安全以保护对静态变量的多线程访问