简体   繁体   English

如何使状态变量线程安全

[英]How to make state variable thread safe

Suppose I have a class having static member variable.There are two synchronized methods,static and instance, present in that class and both the methods are trying to modify the value of static member variable. 假设我有一个具有静态成员变量的类。该类中存在两种同步方法,即static和instance,这两种方法都试图修改static成员变量的值。 First thread is having lock on object of that class , so first thread can access both static synchronized and instance synchronized method. 第一个线程锁定了该类的对象,因此第一个线程可以访问静态同步方法和实例同步方法。 Second thread is having class level lock , so it can access only static synchronized method. 第二个线程具有类级别的锁,因此它只能访问静态同步方法。 In this scenario , how to achieve thread safety. 在这种情况下,如何实现线程安全。

Either add an additional synchronized block to the instance method, that synchronized on the class object, or use an additional lock object. 将一个额外的synchronized块添加到实例方法上,该块在类对象上同步,或者使用其他锁对象。 The following listing shows the former: 以下清单显示了前者:

class Foo {
    private static Set<String> state = new HashSet<>();
    public static synchronized void bar(String item) {
        state.add(item);
    }
    public /* synchronized */ baz(String item) {
        synchronized (Foo.class) {
            state.add(item);
        }
    }
}

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

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