Machine-translated by Google. Questions are authored in English.
Top

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);
    }
}

  • A.Exactly 10000
  • B.A compile error
  • C.Some value from 10000 to 20000; 20000 is not guaranteed
  • D.Exactly 20000

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.