两个同步方法同时执行 [英] Do two synchronized methods execute simultaneously

查看:380
本文介绍了两个同步方法同时执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4种方法( m1 m2 m3 m4 )。方法 m1 m2 m3 synchronized 方法。此外,我有4个线程 t1 t2 t3 t4 分别。

I have 4 methods (m1, m2, m3 and m4) in a class. Method m1, m2 and m3 are synchronized methods. Also, I have 4 threads t1, t2, t3 and t4 respectively.

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

If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously? If not what would be the state of t2?

推荐答案


如果t1访问m1方法(同步方法),可以同时进行线程访问m2方法(同步方法)吗?

synchronized 关键字适用于对象级别,只有一个线程可以保存对象的锁定。因此,只要你谈论同一个对象,那么没有 t2 将等待 t1 释放进入 m1 时获得的锁。

The synchronized keyword applies on object level, and only one thread can hold the lock of the object. So as long as you're talking about the same object, then no, t2 will wait for t1 to release the lock acquired when it entered m1.

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

The thread can however release the lock without returning from the method, by calling Object.wait().


如果没有,那么t2的状态是什么?

它会坐稳等待 t1 释放锁(从方法返回或调用 Object.wait())。具体来说,它将在 BLOCKED

It would sit tight and wait for t1 to release the lock (return from the method or invoke Object.wait()). Specifically, it will be in a BLOCKED state.


线程的线程状态阻止等待监视器锁定。处于阻塞状态的线程正在等待监视器锁定以在调用 Object.wait 之后输入同步块/方法或重新输入同步块/方法。

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

这篇关于两个同步方法同时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆