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

Discussion

Sample40 is run - what will be the output?

public class Sample40
{
    static class Slot
    {
        int value;
        synchronized void set(int v) { value = v; }
        synchronized int get() { return value; }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Slot one = new Slot(), two = new Slot();
        Thread a = new Thread(() -> one.set(1));
        Thread b = new Thread(() -> two.set(2));
        a.start(); b.start(); a.join(); b.join();
        System.out.println(one.get() + "" + two.get());
    }
}

  • A.21
  • B.00
  • C.Either 12 or 00, depending on visibility
  • D.12

Answer: D

The two threads touch different Slot objects, so their synchronized methods lock different monitors and never contend. Each write lands in its own object, and the joins publish both to main, so the reads return 1 and 2. Locking different instances would only be a problem if they shared state.

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

Post your comment

Please log in or register to post a comment.