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

Threads - Finding the output Questions and Answers

41.

Sample41 is run - what will be the output?

public class Sample41
{
    static final StringBuilder LOG = new StringBuilder();

    public static void main(String[] args) throws InterruptedException
    {
        Runnable job = () -> { for (int i = 0; i < 1000; i++) LOG.append('x'); };
        Thread a = new Thread(job), b = new Thread(job);
        a.start(); b.start(); a.join(); b.join();
        System.out.println(LOG.length());
    }
}

Answer: A

StringBuilder makes no attempt at thread safety, so two threads appending concurrently can corrupt its internal length and array; the result may be short, or an ArrayIndexOutOfBoundsException from inside append. The joins order the print but cannot repair the damage. StringBuffer, or a lock, is what makes it safe.

Please log in or register to report this question.

42.

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

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.

Please log in or register to report this question.

43.

Sample43 is run - what will be the output?

import java.util.*;

public class Sample43
{
    static final Map<Integer, Integer> MAP = new HashMap<>();

    public static void main(String[] args) throws InterruptedException
    {
        Runnable job = () -> { for (int i = 0; i < 1000; i++) MAP.put(i, i); };
        Thread a = new Thread(job), b = new Thread(job);
        a.start(); b.start(); a.join(); b.join();
        System.out.println(MAP.size());
    }
}

Answer: C

Both threads write the same 1000 keys, so a correct result would be a size of 1000, but HashMap is unsynchronized and concurrent structural modification can leave the table in an inconsistent state. The size may be wrong and entries may be lost. ConcurrentModificationException guards iteration, not concurrent puts.

Please log in or register to report this question.

44.

Sample44 is run - what will be the output?

import java.util.concurrent.*;

public class Sample44
{
    static final ConcurrentMap<String, String> CACHE = new ConcurrentHashMap<>();

    static class Filler implements Runnable
    {
        public void run()
        {
            for (int i = 0; i < 400; i++)
            {
                CACHE.put("key" + i, "value");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Thread one = new Thread(new Filler()), two = new Thread(new Filler());
        one.start(); two.start();
        one.join(); two.join();
        System.out.println(CACHE.keySet().size());
    }
}

Answer: D

The map is safe under concurrent writes, so both threads put the same 400 keys and the later put for each simply replaces the earlier value. A map holds one mapping per key, and keySet is a view of those keys, so the answer is 400 whichever order the writes happen in.

Please log in or register to report this question.

45.

Sample45 is run - what will be the output?

public class Sample45
{
    public static void main(String[] args) throws InterruptedException
    {
        final Object gate = new Object();
        Thread waiter = new Thread(() ->
        {
            synchronized (gate)
            {
                try { gate.wait(); }
                catch (InterruptedException e) { System.out.println("interrupted"); }
            }
        });
        waiter.start();
        Thread.sleep(100);
        waiter.interrupt();
        waiter.join();
    }
}

Answer: A

wait is one of the documented blocking calls that respond to an interrupt by throwing InterruptedException, so the waiter leaves the wait set, re-acquires the monitor and runs its catch block. Interruption is therefore the way out of a wait that will never be notified.

Please log in or register to report this question.

46.

Sample46 is run - what will be the output?

public class Sample46
{
    static volatile boolean running = true;

    public static void main(String[] args) throws InterruptedException
    {
        Thread worker = new Thread(() ->
        {
            while (running) { }
            System.out.println("stopped");
        });
        worker.start();
        Thread.sleep(100);
        running = false;
        worker.join();
    }
}

Answer: B

A write to a volatile field is guaranteed visible to any later read of it, so the worker's loop sees the change and exits. Without volatile the read could be hoisted out of the loop and the thread might spin for ever, which is exactly the bug the keyword exists to prevent.

Please log in or register to report this question.

47.

Sample47 is run - what will be the output?

public class Sample47 extends Thread
{
    private boolean entered;

    public void run()
    {
        entered = true;
        System.out.println("body");
    }

    public static void main(String[] args) throws InterruptedException
    {
        Sample47 task = new Sample47();
        task.join();
        System.out.println("after " + task.entered);
    }
}

Answer: C

join waits while the thread is alive, and a thread that has never been started is not alive, so the call returns immediately. run() never executes because start was never called, so the flag is still false and only main's line appears.

Please log in or register to report this question.

48.

Sample48 is run - what will be the output?

public class Sample48
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread reporter = new Thread(new Runnable()
        {
            public void run() { System.out.print("work "); }
        });
        reporter.start();
        for (int attempt = 0; attempt < 3; attempt++)
        {
            reporter.join();
        }
        System.out.print("done");
    }
}

Answer: D

join on a thread that has already died returns at once, so joining three times is harmless and does not run the body again. Only start() is restricted to a single call; join may be made by any number of threads any number of times.

Please log in or register to report this question.

49.

Sample49 is run - what will be the output?

public class Sample49
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread t = new Thread(() ->
        {
            try { Thread.sleep(1000); System.out.println("slept"); }
            catch (InterruptedException e) { System.out.println("cut short"); }
        });
        t.interrupt();
        t.start();
        t.join();
    }
}

Answer: A

Interrupting a thread that has not been started has no lasting effect: the status belongs to a live thread, and starting it begins with the flag clear. So the worker sleeps its full second and prints slept. Moving the interrupt after start is what would cut it short.

Please log in or register to report this question.

50.

Sample50 is run - what will be the output?

public class Sample50
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread t = new Thread(() ->
        {
            long n = 0;
            while (!Thread.currentThread().isInterrupted()) n++;
            System.out.println("noticed");
        });
        t.start();
        Thread.sleep(50);
        t.interrupt();
        t.join();
    }
}

Answer: B

The loop consults the interrupt status on every pass, so setting the flag makes the condition false and the thread leaves the loop and prints. Nothing is thrown, because the thread was never inside a blocking call; polling the flag is how a computation-bound task stays interruptible.

Please log in or register to report this question.

Loading…

Topics

    No topic!
Tags: Threads - Finding the output Questions and Answers || Threads - Finding the output MCQ Questions and Answers || Threads - Finding the output GK Questions and Answers || Threads - Finding the output GK MCQ Questions || Threads - Finding the output Multiple Choice Questions and Answers || Threads - Finding the output GK || GK on Threads - Finding the output || Java Programming Questions and Answers || Java Programming MCQ Questions and Answers || Java Programming GK Questions and Answers || GK on Java Programming