简化Java中的同步块 [英] Simplification of synchronized block in Java

查看:115
本文介绍了简化Java中的同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

围绕Java中的同步块的概念,我遇到了一些麻烦.我觉得我对同步方法已经足够了解.因此,我想到了一个类比来帮助我从同步方法的角度理解同步块.请让我知道我建议的对等是否正确.另外,我现在仅针对非静态同步块提到了这一点.但是,也欢迎使用静态同步块上的点.

I'm having some trouble wrapping my head around the concept of synchronized blocks in Java. I feel I have understood synchronized methods well enough. So I thought of an analogy to help me understand synchronized blocks in terms of synchronized methods. Please let me know if this equivalence that I have proposed is correct. Also, I have only mentioned this for a non-static synchronized block for now. However, points on static synchronzied blocks are also welcome.

public void method() 
{
    //code snipppet A

synchronized(objRef) 
{ 
    //code snipppet B
}
    //code snipppet C
}

等同于

public void method() {
//code snippet A
objRef.sync_method();
//code snippet C
}

在objRef类中:

public synchronized void sync_method() {
//code snippet B
}

此类推基于同步块的行为与同步方法一样的逻辑.这意味着一旦某个线程获得了对监视器的锁定,就不会允许其他线程干预其执行.线程只有在完成执行整个同步方法后才放弃控制.

This analogy is based on the logic that synchronized blocks behave just as synchronized methods do. Meaning that once a thread acquires a lock on the monitor, it does not allow other threads to interfere in its execution. The thread relinquishes control only once it has finished executing the entire synchronized method.

推荐答案

您应该注意到,有两个两个Java中同步块的类型(对象同步和类同步).有两种同步方法(静态和非静态方法)及其等效的同步块(分别为类和对象同步块). 假设我们有:

You should notice that there are two types of synchronized block in Java (object synchronize and class synchronize). There are two synchronized methods (static and non-static methods) and their equivalent synchronized blocks (Class and Object Synchronized blocks respectively). assume we have:

class MyClass{
public synchronized static void syncStaticMethod(){...}
public synchronized void syncNonStaticMethod(){...}
}


MyClass objRef = new MyClass();

1.对象同步:

public void method() {synchronized(objRef) { ... }}

等同于

 public void method() {objRef.syncNonStaticMethod();}

2.类同步:

 public void method() {synchronized(MyClass.class) { ... }}

等同于

   public void method() {MyClass.syncStaticMethod();}

这篇关于简化Java中的同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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