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 CollectionsSynchronizedSetExample3 { private static AtomicInteger atomicInteger = new AtomicInteger(); public static void main(String[] args) throws InterruptedException { Set
s = new HashSet<>(); Set
set = Collections.synchronizedSet(s); System.out.println("initial set size: " + set.size()); final ExecutorService e = Executors.newFixedThreadPool(10); for (int i = 0; i < 1000; i++) { e.execute(() -> set.add(atomicInteger.incrementAndGet())); } e.shutdown(); e.awaitTermination(1000, TimeUnit.SECONDS); System.out.println(set.size());//should be 1000 } }
Output