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

Threads - Finding the output Questions and Answers

51.

Sample51 is run - what will be the output?

import java.util.concurrent.*;

public class Sample51
{
    public static void main(String[] args) throws Exception
    {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<Integer> f = pool.submit(() -> 7 / 0);
        try { System.out.println(f.get()); }
        catch (ExecutionException e)
        { System.out.println("failed: " + e.getCause().getClass().getSimpleName()); }
        pool.shutdown();
    }
}

Answer: C

A task's exception cannot be thrown on the submitting thread directly, so the Future wraps it in an ExecutionException and get rethrows that. getCause unwraps the original, which is the ArithmeticException from the division. This is how a failure crosses back from a worker.

Please log in or register to report this question.

52.

Sample52 is run - what will be the output?

import java.util.concurrent.*;

public class Sample52
{
    public static void main(String[] args) throws Exception
    {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Future<?> f = pool.submit(() -> System.out.print("ran "));
        System.out.print(f.get() + " ");
        pool.shutdown();
        System.out.print(pool.isShutdown());
    }
}

Answer: D

Submitting a Runnable gives a Future whose get returns null once the task has finished, because a Runnable produces no value. The get also guarantees the task's own output comes first. shutdown returns immediately and isShutdown then reports true.

Please log in or register to report this question.

53.

Sample53 is run - what will be the output?

import java.util.concurrent.*;

public class Sample53
{
    public static void main(String[] args) throws Exception
    {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        pool.submit(() ->
        {
            try { Thread.sleep(5000); }
            catch (InterruptedException e) { System.out.println("stopped early"); }
        });
        Thread.sleep(100);
        pool.shutdownNow();
    }
}

Answer: A

shutdownNow interrupts the threads running the current tasks as well as refusing new ones, and a task asleep at the time receives InterruptedException. Plain shutdown would only stop new submissions and let the sleep finish.

Please log in or register to report this question.

54.

Sample54 is run - what will be the output?

public class Sample54 extends Thread
{
    public void run()
    {
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException ignored)
        {
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Sample54 sleeper = new Sample54();
        sleeper.start();
        Thread.sleep(200);
        Thread.State observed = sleeper.getState();
        sleeper.interrupt();
        System.out.println(observed);
    }
}

Answer: B

A thread inside a call that will give up after a stated interval reports TIMED_WAITING, which covers sleep, wait with a timeout and join with a timeout. Plain WAITING is for the untimed forms, and BLOCKED is reserved for waiting on a monitor lock.

Please log in or register to report this question.

55.

Sample55 is run - what will be the output?

public class Sample55
{
    static final Object GATE = new Object();

    public static void main(String[] args) throws InterruptedException
    {
        Thread t = new Thread(() ->
        {
            synchronized (GATE)
            {
                try { GATE.wait(); } catch (InterruptedException e) { }
            }
        });
        t.start();
        Thread.sleep(200);
        System.out.println(t.getState());
        synchronized (GATE) { GATE.notifyAll(); }
    }
}

Answer: C

An untimed wait puts the thread in the wait set indefinitely, which is reported as WAITING. It is not BLOCKED, because it is not competing for a lock at that moment; it released the monitor when it called wait and will contend for it again only once notified.

Please log in or register to report this question.

56.

Sample56 is run - what will be the output?

public class Sample56
{
    public static void main(String[] args) throws InterruptedException
    {
        final Object lock = new Object();
        Thread holder = new Thread(() ->
        {
            synchronized (lock)
            {
                try { Thread.sleep(3000); } catch (InterruptedException e) { }
            }
        });
        holder.start();
        Thread.sleep(100);
        Thread waiter = new Thread(() -> { synchronized (lock) { } });
        waiter.start();
        Thread.sleep(100);
        System.out.println(waiter.getState());
        holder.interrupt();
    }
}

Answer: D

The holder keeps the monitor across its sleep, because sleep releases no locks, so the second thread sits at the entrance to the synchronized block. Waiting to acquire a monitor is exactly what BLOCKED means, as distinct from the WAITING that wait() produces.

Please log in or register to report this question.

57.

Sample57 is run - what will be the output?

public class Sample57
{
    public static void main(String[] args)
    {
        System.out.print(Thread.currentThread().isDaemon() + " ");
        System.out.print(new Thread().isDaemon());
    }
}

Answer: A

Correct answer: false false

The main thread is created by the JVM as a user thread, so the first call prints false. A newly constructed thread inherits its daemon status from the thread that created it, and here that is main - so the second prints false as well. The status is inherited at construction and can be changed with setDaemon, but only before the thread is started.

Please log in or register to report this question.

58.

Sample58 is run - what will be the output?

public class Sample58
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread outer = new Thread(() ->
        {
            Thread inner = new Thread(() -> { });
            System.out.println(inner.isDaemon());
        });
        outer.setDaemon(true);
        outer.start();
        outer.join();
    }
}

Answer: B

Daemon status is inherited: a new thread is a daemon exactly when the thread that created it is one. The outer thread was made a daemon before being started, so the thread it creates is a daemon too, without any call to setDaemon.

Please log in or register to report this question.

59.

Sample59 is run - what will be the output?

public class Sample59
{
    public static void main(String[] args) throws InterruptedException
    {
        final Object gate = new Object();
        long start = System.currentTimeMillis();
        synchronized (gate) { gate.wait(300); }
        System.out.println(System.currentTimeMillis() - start >= 300);
    }
}

Answer: C

A timed wait returns when the interval elapses even though no notification ever arrives, so the elapsed time is at least the timeout. That is the difference from the untimed form, which would block for ever here. The monitor is held, so the call itself is legal.

Please log in or register to report this question.

60.

Sample60 is run - what will be the output?

public class Sample60
{
    static final Object GATE = new Object();

    public static void main(String[] args)
    {
        synchronized (GATE) { GATE.notifyAll(); }
        System.out.println("sent");
    }
}

Answer: D

notify and notifyAll simply do nothing when the wait set is empty; there is no error and nothing is remembered for a future waiter. The call is legal because the monitor is held, and main continues straight to its print.

Please log in or register to report this question.

Loading…

Other Subjects

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