Suppose 2 threads - A
and B
executing the method addTenThings()
at the same time. They can do it, as the method isn't synchronized.
Then if during the time the thread A
is executing toString()
method of set
, thus iterating over it, the thread B
is still executing the loop, and invokes the add()
method, that might cause ConcurrentModificationException
, as both the threads are operating on the same set
only. Nothing stops a thread to execute the add(r.nextInt())
statement, while a different thread is executing the print
statement in the method.