如果监视器已被锁定,对Java中的同步块的请求将会发生什么? [英] what will happen to the request for synchronized block in java if monitor is already locked?

查看:76
本文介绍了如果监视器已被锁定,对Java中的同步块的请求将会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果当前线程持有监视器,那么来自不同线程的同步块请求将发生什么情况? 例子: 下面说的是同步块:

What will happen to the request for synchronized block from different threads, if current threads holds the monitor? example: say below is the synchronized block:

ABC.java:

public class ABC {

    ...
    public void setValue(){
        Example object = Example.getinstance();
        // Example is a singleton class which maintains the arraylist of objects of class ABC 
        synchronized (object) {
            object.storeObject(this);
        }
    }

    ...
}

假设有三个线程T1,T2,T3正在为ABC类创建对象,例如:obj1,obj2,obj3.并且所有三个对象都在调用ABC类的setValue方法: 例子: Thread T1: obj1.setValue() Thread T2: obj2.setValue() Thread T3: obj3.setValue()

suppose there are three threads T1,T2,T3 which is creating objects for ABC class e.g: obj1,obj2,obj3. and all three objects are calling setValue method of ABC class: example: Thread T1: obj1.setValue() Thread T2: obj2.setValue() Thread T3: obj3.setValue()

如果第一个请求(线程T1)正在处理中,请求(T2和T3)将如何处理?它会被拒绝,还是其他线程将被挂起或排队?如果被拒绝或暂停,该如何处理所有请求?

What will happen to the requests(T2 & T3) if first request(Thread T1) is under processing? Will it be rejected, or other threads will be suspended or Queued up? If rejected or suspended , how to process all the request?

推荐答案

一个线程一次获取锁.如果该锁已被使用,则其他所有请求线程都会阻塞-即暂停执行-直到该锁释放为止.您可以将其视为排队",请记住,这并不完全是这样:与synced关键字一起使用的内在锁是不公平的,这取决于OS调度程序来决定哪个线程先行.它不必根据首先询问的人进行选择,它可以选择正在等待该锁的任何线程.

One thread acquires the lock at a time. If the lock is already taken, any other requesting threads block - that is, pause execution - until the lock is free. You can think of it as "queueing up", keeping in mind that that is not exactly what happens: the intrinsic locks used with the synchronized keyword are not fair, it's up to the OS scheduler to decide which thread goes first. It doesn't have to choose according to who asked first, it can pick any of the threads that are waiting on that lock.

在您的示例中,所有线程都将有机会获得锁(它们都不会被关闭或超时),但是并没有告诉他们将执行该锁的顺序.

In your example the threads will all get a chance to acquire the lock (none of them get turned away or timed out), but there's no telling what order they will do it in.

这篇关于如果监视器已被锁定,对Java中的同步块的请求将会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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