Discussion
Sample19 is run - what will be the output?
public class Sample19
{
static int count = 0;
public static void main(String[] args) throws InterruptedException
{
Runnable r = () -> { for (int i = 0; i < 10000; i++) count++; };
Thread a = new Thread(r), b = new Thread(r);
a.start(); b.start();
a.join(); b.join();
System.out.println(count);
}
}
Answer: C
The joins guarantee both threads have finished, so the print is not the problem; the increments are. count++ reads, adds and writes, and two threads can interleave those steps and lose updates, so the total can be anything from 10000 up to 20000. Only synchronization or an AtomicInteger makes 20000 certain.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development