在单个语句上同步? [英] synchronization on single statement?

查看:67
本文介绍了在单个语句上同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个只有这样一条语句的getter方法

if I have a getter method that has only one statement like this

public class NumberClass{
    int number;

    public int getNumber() {
        return number;
    }
    ...
}

并且有多个线程访问此方法,我是否必须同步此方法,或者因为它只有一个语句而没有必要?

and multiple threads access this method, do I have to synchronize this method or it is not necessary since it has only one statement??

推荐答案

我必须同步此[get]方法,否则没有必要,因为它只有一个语句?

I have to synchronize this [get] method or it is not necessary since it has only one statement??

它与1个或多个语句无关.这取决于该值是否已在另一个线程中更新,以及是否要让所有线程看到一致的值.

It has nothing to do with 1 or more statements. It depends on whether or not the value has been updated in another thread and if you want all of the threads to see a consistent value.

如果在线程1中更新了number字段,则线程2可能会获得原始值或新值,具体取决于更新的同步方式.要正确发布值,set和get方法都需要synchronized.

If the number field was updated in thread1, then thread2 may get either the original value or the new value depending on how the update was synchronized. To have the value published appropriately both the set and get methods need to synchronized.

如果您只是想共享一个int值,则将number字段标记为volatile将可行,或者使用AtomicInteger在多个线程之间可靠地共享该值可能更合适.

If you are just trying to share an int value then marking the number field as being volatile would work or using an AtomicInteger to share the value between multiple threads reliably may be more appropriate.

private volatile int number;

或使用:

private AtomicInteger number = new AtomicInteger();

这篇关于在单个语句上同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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