Ensuring Thread-Safety of an ArrayList in Java
Issue: An ArrayList used to store Thread objects (RaceCar) in a racing simulation requires thread safety to maintain the correct order of finishers. The initial attempt to synchronize the ArrayList using Collections.synchronizedCollection() resulted in a compiler error.
Analysis:
Collections.synchronizedCollection() can only synchronize non-List Collection implementations. To synchronize an ArrayList specifically, use Collections.synchronizedList().
Solution:
<code class="java">finishingOrder = Collections.synchronizedList(new ArrayList<>(numberOfRaceCars));</code>
This code correctly creates a thread-safe ArrayList to store RaceCar objects and maintain the order of finishers.
The above is the detailed content of How Can You Ensure Thread-Safety for an ArrayList of Thread Objects in Java?. For more information, please follow other related articles on the PHP Chinese website!