简体   繁体   中英

Sharing an int or an integer object between multiple threads in Java

I have a multithreaded program that includes data structures like ConcurrentHashMap and ConcurrentLinkedList , however I also need every thread to access a shared integer value. The threads themselves are custom thread classes I've made that extend class Thread . My two concerns here are:

  • How can I make each thread see the same integer value? I don't think a primitive int would work as it would not be "passed by reference" (or rather passed by value of the object pointer). The integer needs to be mutable and any changes to one integer by a thread needs to be seen by all the other threads. Would using an Integer Object fix this, what about AtomicInteger ?

  • What should I use to preserve thread safety? Each thread will check the integer everytime a loop in them runs but it will change the integer when a thread has finished it's task and is about to return.

Thanks in advance!

You should use an AtomicInteger .

I would however consider AtomicInteger as a fairly low level primitive. I would question the design. Have you considered using ExecutorService , Callable , Futures , Semaphore , CountDownLatch , the Fork/Join framework or other classes from the high level java.util.concurrent API?

You can use AtomicInteger . It supports many atomic operation. For eg addAndGet , decrementAndGet , etc. AtomicInteger does extend Number , so you can pass it to methods that operate on numerically based classes.

Use an AtomicInteger . I suggest you to make it final and then use operations on the AtomicInteger such as incrementAndGet

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