简体   繁体   English

java同步中对象锁的捕获和释放是如何工作的?

[英]How does capturing and releasing of lock of an object works in java synchronization?

If a thread is executing a synchronized method, will it release the lock of that object before fully completing the execution of that method ?如果线程正在执行同步方法,它会在完全完成该方法的执行之前释放该对象的锁吗? If yes, in what kind of case ?如果是,在什么样的情况下?

If one thread(A) is executing synchronized method and at same time other thread(B) tries to access same synchronized method (or any other synchronized method in that object) it will go to BLOCKED state, but if the other thread(B) tries to access non-synchronized method will it get the execution before the first thread(A) completes the execution of the synchronized method ?如果一个线程(A)正在执行同步方法,同时另一个线程(B)尝试访问相同的同步方法(或该对象中的任何其他同步方法),它将进入BLOCKED状态,但如果另一个线程(B)尝试访问非同步方法是否会在第一个线程(A)完成同步方法的执行之前获得执行? Or it will get the execution only after the first thread(A) completes the execution of synchronized method ?还是只有在第一个线程(A)完成同步方法的执行后才会执行?

A synchronized method is just a shortcut way of writing a synchronized block (see https://stackoverflow.com/a/26676499/801894 ). synchronized方法只是编写同步的快捷方式(参见https://stackoverflow.com/a/26676499/801894 )。 So, no matter whether you are talking about a synchronized instance method, or a synchronized static method or a synchronized block, you really are talking about the same thing in all three cases.因此,无论您是在谈论同步实例方法,还是同步静态方法或同步块,您实际上在所有三种情况下都在谈论同一件事。

Java will never allow more than one thread to be synchronized on the same object at the same time. Java 永远不会允许多个线程同时在同一个对象上进行同步。 The only tricky part of understanding that rule is to know that if a thread calls foo.wait() from inside a synchronized(foo){...} block, then the thread will not be synchronized for some interval of time while it is inside the foo.wait() call.理解该规则的唯一棘手部分是要知道,如果一个线程从synchronized(foo){...}块内部调用foo.wait() ,那么该线程在一段时间内不会同步在foo.wait()调用中。 But, it is guaranteed that the thread will synchronize on foo again before the foo.wait() call returns.但是,可以保证在foo.wait()调用返回之前线程将再次在foo同步。

The only other way a thread can give up its synchronization of foo is to leave the synchronized(foo) {...} block altogether.线程可以放弃其foo同步的唯一另一种方法是完全离开synchronized(foo) {...}块。

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

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