简体   繁体   English

同步块内的同步块

[英]Synchronized block inside synchronized block

May I include a synchronized block inside another one for synchronizing another object? 我可以在另一个中包含一个同步块来同步另一个对象吗?

Example: 例:

synchronized(myObjetc1){
    // code
    synchronized(myObjetc2){
        // code         
    }           
}

If so, still, is it a correct technique or is it too risky? 如果是这样,它仍然是一种正确的技术还是风险太大?

It will be fine if you synchronize in the same order everywhere else. 如果你在其他地方以相同的顺序同步,那就没问题了。

If some other thread were to execute the following code 如果其他一些线程要执行以下代码

synchronized(myObjetc2){
    // code
    synchronized(myObjetc1){
        // code         
    }           
}

you might get a deadlock. 你可能会遇到僵局。

Assuming the variables above are referencing the same objects, consider the following case. 假设上面的变量引用相同的对象,请考虑以下情况。 The first thread (your code) locks the monitor on myObjetc1 . 第一个线程(您的代码)将监视器锁定在myObjetc1 The thread scheduler switches thread context. 线程调度程序切换线程上下文。 The second thread (the above code) locks the monitor on myObjetc2 . 第二个线程(上面的代码)将监视器锁定在myObjetc2 The thread scheduler switches thread context. 线程调度程序切换线程上下文。 The first thread attempts to lock the monitor on myObjetc2 . 第一个线程尝试将监视器锁定在myObjetc2 It has to wait because the second thread has it. 它必须等待,因为第二个线程有它。 The thread scheduler switches context. 线程调度程序切换上下文。 The second thread attempts to lock the monitor on myObjetc1 . 第二个线程尝试将监视器锁定在myObjetc1 It has to wait because the first thread has it. 它必须等待,因为第一个线程有它。 Boom! 繁荣! Deadlock. 僵局。

Yes, you can do it. 是的,你可以做到。

Till the time you are following lock rules and doing so solves your requirement, its Fine. 直到您遵守锁定规则并且这样做才能解决您的要求,即罚款。

However, many times something like this invites DeadLock problem, if done incorrectly. 但是,很多时候这样的事情会引起DeadLock问题,如果做错了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM