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

Threads - Finding the output Questions and Answers

21.

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

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.

Please log in or register to report this question.

22.

Sample22 is run - what will be the output?

public class Sample22
{
    public static void main(String[] args)
    {
        Thread sweeper = new Thread(() ->
        {
            while (true) { }
        });
        sweeper.setDaemon(true);
        sweeper.start();
        System.out.println("main ends");
    }
}

Answer: B

The JVM stops when the only threads left are daemons, and main returning leaves exactly that. The sweeper is abandoned mid-loop with no chance to clean up, which is why work that must complete belongs on a non-daemon thread. Marking it a daemon before start is the correct order.

Please log in or register to report this question.

23.

Sample23 is run - what will be the output?

public class Sample23 extends Thread
{
    public void run()
    {
        System.out.print("swept ");
    }

    public static void main(String[] args) throws InterruptedException
    {
        Sample23 sweeper = new Sample23();
        sweeper.setDaemon(true);
        sweeper.start();
        sweeper.join();
        System.out.print("exit");
    }
}

Answer: C

Being a daemon changes only what happens at shutdown; it does not stop the thread running or make join unreliable. The join holds main until the worker has died, so the order here is fully determined. The earlier version without a join is the unpredictable one.

Please log in or register to report this question.

24.

Sample24 is run - what will be the output?

public class Sample24 implements Runnable
{
    public void run() throws InterruptedException
    {
        Thread.sleep(100);
    }

    public static void main(String[] args)
    {
        new Thread(new Sample24()).start();
    }
}

Answer: D

Runnable declares run() with no throws clause, and an override may not add a checked exception to the method it implements. The sleep therefore has to be wrapped in a try-catch inside run(). Runnable declares only run(); start() belongs to Thread.

Please log in or register to report this question.

25.

Sample25 is run - what will be the output?

public class Sample25
{
    public static void main(String[] args)
    {
        Runnable r = () -> System.out.println("go");
        r.start();
    }
}

Answer: A

Runnable declares run() and nothing else, so there is no start() to call on it; only Thread has that. The lambda itself is fine, since Runnable is a functional interface. Wrapping it as new Thread(r).start() is what launches it.

Please log in or register to report this question.

26.

Sample26 is run - what will be the output?

public class Sample26 extends Thread
{
    private final String label = "report";
    private int calls;

    public void run(String prefix)
    {
        calls++;
        System.out.println(prefix + label + calls);
    }

    public static void main(String[] args) throws InterruptedException
    {
        Sample26 task = new Sample26();
        task.start();
        task.join();
        System.out.println("finished " + task.calls);
    }
}

Answer: B

Adding a parameter creates an overload, not an override, so Thread's own no-argument run() is what start() invokes. That inherited method has no Runnable to delegate to and does nothing, so the counter is never incremented and only main's line appears. @Override on the method would have turned the mistake into a compile error.

Please log in or register to report this question.

27.

Sample27 is run - what will be the output?

public class Sample27
{
    public static void main(String[] args) throws InterruptedException
    {
        Object lock = new Object();
        Thread t = new Thread(() ->
        {
            synchronized (lock)
            {
                System.out.println("worker");
                lock.notify();
            }
        });
        synchronized (lock)
        {
            t.start();
            lock.wait();
            System.out.println("main");
        }
    }
}

Answer: C

main holds the lock and calls wait, which releases it and parks main in the wait set, so the worker can enter, print and notify. main then has to re-acquire the monitor, which it can only do after the worker leaves its synchronized block, so its print always comes second.

Please log in or register to report this question.

28.

Sample28 is run - what will be the output?

public class Sample28 extends Thread
{
    static final Object GATE = new Object();

    public void run()
    {
        synchronized (GATE)
        {
            GATE.notifyAll();
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Sample28 signaller = new Sample28();
        signaller.start();
        signaller.join();

        synchronized (GATE)
        {
            GATE.wait();
        }
        System.out.println("woken");
    }
}

Answer: D

A monitor keeps no record of notifications. The join guarantees the worker has already notified and died before main waits, so the signal is gone and nothing will ever wake main. This lost-wakeup is why the condition must be tested inside the lock before waiting at all.

Please log in or register to report this question.

29.

Sample29 is run - what will be the output?

public class Sample29
{
    static boolean ready = false;

    public static void main(String[] args) throws InterruptedException
    {
        Object lock = new Object();
        new Thread(() ->
        {
            synchronized (lock) { ready = true; lock.notifyAll(); }
        }).start();
        synchronized (lock)
        {
            while (!ready) lock.wait();
        }
        System.out.println("ready");
    }
}

Answer: A

The flag is tested inside the lock before waiting, so if the worker has already run, the while loop never waits at all and main proceeds. If it has not, wait releases the lock until the notify arrives. That is precisely why the condition-in-a-loop idiom is immune to the lost wakeup of the previous example.

Please log in or register to report this question.

30.

Sample30 is run - what will be the output?

import java.util.concurrent.atomic.AtomicInteger;

public class Sample30
{
    static AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException
    {
        Runnable r = () -> { for (int i = 0; i < 10000; i++) count.incrementAndGet(); };
        Thread a = new Thread(r), b = new Thread(r);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println(count.get());
    }
}

Answer: B

incrementAndGet performs the read, add and write as one indivisible operation, so no update can be lost however the two threads interleave. With both joins completed before the print, the total is exactly 20000. This is the fix for the plain and the volatile counter alike.

Please log in or register to report this question.

Loading…
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