简体   繁体   中英

Multiple threads get value of x variable but only one thread can change the value of x variable at a time

In Java, I have a global variable x, what should I use to allows many threads get the value of x at a time but only one thread can change the value of x variable at a time?

Any example? Thanks.

如果要允许多个并发读取,则需要使用ReadWriteLockReentrantReadWriteLock类实现该特定接口)来保护访问。

In this case you should be able to use the classes in java.util.concurrent.atomic . These classes are containers for a single value that allow lock-free access. If you don't need a compare-and-swap operation you can use a volatile field as long as you're using at least java 1.5.

You can use a ReadWriteLock to acheive this. Java java.util.concurrent.locks package provides different types of locks. You can use ReentrantReadWriteLock from this package. Code samples can be found in javadoc.

If the global variable is a basic data type, AtomicLong, AtomicInt etc in java.util.concurrent.atomic package should also be able to solve the usecase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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