answer : A
Enhanced loop is actually using itterator under the hood.
According to the Java API documentation [API 2014]:
It is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.
But acording to sleep time delay the non-thread loop itterator will start earlier. But itettrator works directly with arraylist and itterator has to reflect the data modification.
Answer A is more preferable.
is a dificult question, if run normaly D is correct, but if run with debug option step by step can modify answers because the time in breackpoint can modified output.
But
The main method in the Example class is creating a concurrent list cp with the elements "1", "2", "3", "4". Then, it creates a Runnable that sleeps for 150 milliseconds, changes the fourth element of the list to "four", and prints the list. After that, it creates a new thread t with the Runnable and starts it. While the thread t is sleeping and before it changes the fourth element of the list, the main thread enters a loop and starts printing the elements of the list one by one, sleeping 100 milliseconds between each print. Therefore, it's likely that the main thread prints the first elements of the list before the thread t gets a chance to change the fourth element. However, the exact behavior may vary depending on the operating system's thread scheduler and when exactly the threads are scheduled to run.
NOTICE: foreach print 3, 4 because CopyOnWriteArrayList when is currently itering, this iterations is on a copy of original list, not in the same list. So when change 4 by four no reflected in the copy that iterate.
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
ASPushkin
6 months, 2 weeks agomendjijet
12 months agod7bb0b2
1 year, 1 month agod7bb0b2
1 year agoOmnisumem
1 year, 4 months agoStavok
1 year, 6 months agotmuralimanohar
1 year, 7 months agoMukes877
1 year, 7 months agoKMLA
1 year, 11 months ago