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

Discussion

Sample21 is run - what will be the output?

public class Sample21
{
    static int tally = 0;
    static final Object LOCK = new Object();

    public static void main(String[] args) throws InterruptedException
    {
        Runnable job = () ->
        {
            for (int i = 0; i < 2000; i++)
            {
                synchronized (LOCK) { tally++; }
            }
        };
        Thread p = new Thread(job), q = new Thread(job);
        p.start(); q.start();
        p.join(); q.join();
        System.out.println(tally);
    }
}

  • A.4000
  • B.Some value from 2000 to 4000
  • C.2000
  • D.A compile error

Answer: A

Each increment happens while holding the lock on LOCK, so no two can interleave and none is lost. Releasing a monitor also publishes the writes, and the joins mean both loops have finished before the print, so 4000 is guaranteed. A private final lock object is preferred to locking the class.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.