java 静态 多线程,Java多线程访问静态变量

在多线程环境中,直接访问静态变量可能导致内存冲突。为避免这种情况,建议将静态变量的访问包裹在同步方法中,如`synchronized`关键字,或者使用`ReentrantLock`。此外,标记静态变量为`volatile`可以确保各线程间可见性,防止缓存导致的不一致。这确保了在并发访问时的数据正确性。
摘要由CSDN通过智能技术生成

How can I access static variable from many thread simultaneously.

If I have a class like

Class A {

public static boolean FLG=false;

.....................

....................

}

And I need to access the value from thread 1 like

....................

public void run() {

boolean t1=A.FLG;

..................

}

and from thread 2 I need to set value like

....................

public void run() {

A.FLG=true;

..................

}

Does this cause memory violation ?. If so what is the recommended method to handle such a situation?.

解决方案

Wrap the static variable in a synchronized method and call the method as you like

public static synchronized void method1(){

//Whatever

}

public static synchronized void method2(){

//Whatever again

}

Note that there are other ways to synchronize access to a method. They are considered more efficient in environments busy threads accessing the same methods.

Check the ReentrantLock class. There are also answers for when to use synchronized and RentrantLock and many more information that could be found through google.

Also as peter's answer and muel's comment suggests. Marking the boolean variable as volatile should be helpful. volatile boolean variables will NOT cache it's initial value (false or true). The JVM could do that occasionally which could be unexpected by the programmer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值