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

Discussion

Sample42 is run - what will be the output?

public class Sample42 extends Thread
{
    static final StringBuffer SINK = new StringBuffer();

    public void run()
    {
        int written = 0;
        while (written < 750)
        {
            SINK.append('.');
            written++;
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Sample42 p = new Sample42(), q = new Sample42();
        p.start(); q.start();
        p.join(); q.join();
        System.out.println(SINK.length());
    }
}

  • A.An ArrayIndexOutOfBoundsException from inside append
  • B.1500
  • C.An unpredictable length below 1500
  • D.750

Answer: B

StringBuffer synchronizes its methods, so each append is atomic and none is lost; with 750 from each thread the length is exactly 1500. Per-method synchronization would still not make a sequence of calls atomic, and the interleaving of the characters remains unspecified, which does not matter when they are identical.

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

Post your comment

Please log in or register to post a comment.