如果我将静态锁放在实例方法中会怎样? [英] What will happen if I put a static lock in a instance method?

查看:89
本文介绍了如果我将静态锁放在实例方法中会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是线程新手,目前正在阅读线程同步一章.我对线程锁定中的一种情况有疑问

I am thread newbie and am currently going through the thread synchronization chapter. I have a question regarding one scenario in thread locking

这是我所知道的:

1:当我在实例方法(即)中放置实例锁时

1: When I put a instance lock in a instance method(i.e.)

private Object lock1= new Object();
private Object lock2 = new Object();
void f1(){
    synchronized (lock1) {

    }
}
void f2(){
    synchronized (lock2 ) {

    }
}

void f4(){
    synchronized (lock2 ) {

    }
}
void f3(){
    synchronized (lock1) {

    }
}

这里将发生的事情是,如果有一个类X的对象A被多个线程共享,并且某个线程t1正在执行f1的块,那么直到t1出现f1块,所有其他线程都试图进入函数f3,,f1将被阻止. f2和f4也是这种情况.

Here what will happen is that, if there is object A of a class X being shared by multiple threads, and some thread t1 is executing f1's block, then until t1 comes out f1 block, all the other threads trying to enter function f3,,f1 will be blocked. Same is the case with f2 and f4.

现在,在使用静态锁的情况下,如果一个类具有多个静态方法,并且我们希望对这些方法分别进行锁定而不是对类进行锁定,则将拥有多个静态锁.这些锁将确定将阻止哪些方法.

Now in case of static locks, if a class has multiple static methods, and we want individual locking for those methods rather than class locking, we will have multiple static locks. And those locks will determine, what methods will be blocked.

到目前为止,一切都很好.现在,如果将此静态锁放在实例方法中,那么当同一对象上的两个线程尝试访问该方法时,会发生什么情况?

Up until this point everything is fine. Now If put this static locks in a instance method, what will happen, when two thread on the same object try to access that method?

推荐答案

在实例方法中的static锁上synchronize时,无论哪个线程,只有一个线程将能够进入由该锁控制的临界区.该对象的实例正在使用.

When you synchronize on static locks in instance methods, only one thread would be able to enter the critical section controlled by that lock, regardless on what instance of the object is is using.

如果将lock1设为静态,则即使创建数百个类X的实例,系统范围内也只有一个线程能够运行f1f3,因为所有static成员(包括对象)您在其上锁定的对象在该类的所有实例之间共享.

If you make lock1 static, only one thread systemwide would be able to run f1 or f3, even if you make hundreds of instances of class X, because all static members, including objects on which you lock, are shared among all instances of the class.

这篇关于如果我将静态锁放在实例方法中会怎样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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