同步的Java方法将调用排队吗? [英] do synchronized java methods queue calls?

查看:196
本文介绍了同步的Java方法将调用排队吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关同步方法以及如何将它们引入多线程程序锁定的oracle文档,但是有一点我不清楚. 对已锁定方法的后续调用是否在队列中?

I've read the oracle doc about synchronized methods and how they may introduce a lock to the multithreaded program, but there is one thing that is unclear to me. Are the subsequent calls to an already locked methods queued?

让我们说我们有一堂课:

Lets say we have a class:

class Astore {
    ...
    public synchronized void a() {
        doSomethingTimeConsuming();
    }
    ...
}

和3个调用astore.a()的线程

and 3 threads that call astore.a()

final Astore astore = new Astore();

Thread t1 = new Thread(new Runnable() {
    public void run() { 
        astore.a();
        doSomethingElse();
        astore.a();
    }
});
t1.start();

Thread t2 = new Thread(new Runnable() {
    public void run() {
        astore.a();
    }
});
t2.start();

Thread t3 = new Thread(new Runnable() {
    public void run() {
        astore.a();
    }
});
t3.start();

我不确定我是否正确地编写了示例,但要点是,3个线程几乎同时使用同步方法对同一对象进行了调用.

I'm not sure if I've made the example correctly, but the point is, that 3 threads make a call to the same object with synchronized method almost at the same time.

将操作顺序存储在队列中,以便调用的线程为:

Will the order of operations be stored in a queue so that the threads invoking will be:

  1. t1(最初称为)
  2. t2(在T1之后调用)
  3. t3
  4. 再次
  5. t1(其他线程请求方法时,它已经忙于使用A进行操作了)

我可以安全地假设这是行为,还是不能保证这是顺序(或更糟糕的是,t2和t3可能会以随机顺序被调用)

Can I safely assume that will be the behavior, or there is no guarantee that this will be the order (or even worse, t2 and t3 might get called in random order)

当多个线程可能需要共享数据时(例如,一个套接字服务器的每个活动连接只有一个线程)的最佳实践是什么?我不希望6个客户端在等待第一个客户端完成大量连接时超时上传到共享数据结构)

What is the best practice when multiple threads may need to share data (for instance a socket server with one thread for each active connection - I don't want 6 clients to time out while waiting for the first one to finish a huge upload to a shared data structure)

推荐答案

否,它不会使对该方法的调用排队.

No, it will not queue calls to the method.

如果调用是从已经获得锁的线程进行的(例如,递归调用),那么它将像往常一样进行.

If the call is made from a Thread that already has got the lock (a recursive call, for example), then it will just proceed like normal.

其他试图获取该锁以能够进行调用的线程将保留在那里并等待直到锁被释放.

Other threads that attempt to get the lock to be able to make a call will hold there and wait until the lock is released.

不能保证顺序,请使用公平

The order is not guaranteed, use a fair ReentrantLock if that is important.

这篇关于同步的Java方法将调用排队吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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