Online Java Compiler By
JavaTpoint.com
import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class CollectionsSynchronizedSortedMapExample3 { private static AtomicInteger counter = new AtomicInteger(); public static void main(String... args) throws InterruptedException { SortedMap
m = new TreeMap<>(); SortedMap
map = Collections.synchronizedSortedMap(m); final ExecutorService e = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { e.execute(() -> map.put(counter.incrementAndGet(), (int) (Math.random() * 100))); } e.shutdown(); e.awaitTermination(1000, TimeUnit.SECONDS); System.out.println(map.size());//should be 10 } }
Output