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

Threads - Finding the output Questions and Answers

31.

Sample31 is run - what will be the output?

public class Sample31
{
    static class Counter { int value; synchronized void bump() { value++; } }

    public static void main(String[] args) throws InterruptedException
    {
        Counter one = new Counter(), two = new Counter();
        Thread a = new Thread(() -> { for (int i = 0; i < 5; i++) one.bump(); });
        Thread b = new Thread(() -> { for (int i = 0; i < 5; i++) two.bump(); });
        a.start(); b.start(); a.join(); b.join();
        System.out.println(one.value + " " + two.value);
    }
}

Answer: C

Each thread increments its own Counter, so there is no shared state and no contention at all; the two synchronized methods lock different instances, which does not matter here. Each loop runs five times, so both fields end at 5 and the joins make that visible to main.

Please log in or register to report this question.

32.

Sample32 is run - what will be the output?

import java.util.concurrent.*;

public class Sample32
{
    public static void main(String[] args) throws Exception
    {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> f = pool.submit(() -> "result");
        System.out.println(f.get());
        pool.shutdown();
    }
}

Answer: D

The lambda returns a value, so it is taken as a Callable and submit hands back a Future. get() blocks until the task has completed and then returns its value, which makes the output fully determined. Without the shutdown the pool's non-daemon thread would keep the JVM alive.

Please log in or register to report this question.

33.

Sample33 is run - what will be the output?

import java.util.concurrent.*;

public class Sample33
{
    public static void main(String[] args)
    {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.submit(() -> System.out.println("task"));
    }
}

Answer: A

The task runs and prints, but a pool's worker threads are non-daemon by default and stay alive waiting for more work, so the JVM never reaches the exit condition. Calling shutdown is what lets it finish; forgetting it is a common reason a program appears to hang at the end.

Please log in or register to report this question.

34.

Sample34 is run - what will be the output?

public class Sample34
{
    static ThreadLocal<Integer> seen = ThreadLocal.withInitial(() -> 0);

    public static void main(String[] args) throws InterruptedException
    {
        Runnable r = () ->
        {
            seen.set(seen.get() + 1);
            System.out.print(seen.get());
        };
        Thread a = new Thread(r), b = new Thread(r);
        a.start(); a.join(); b.start(); b.join();
        System.out.print(seen.get());
    }
}

Answer: B

Each thread has its own value, so both workers start from the initial 0, set 1 and print 1. main has never set its own value, so it still reads the initial 0 and prints that. The joins make the order of the three prints deterministic.

Please log in or register to report this question.

35.

Sample35 is run - what will be the output?

public class Sample35
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread t = new Thread(() ->
        {
            try { Thread.sleep(2000); } catch (InterruptedException e) { }
        });
        t.start();
        t.join(100);
        System.out.println(t.isAlive());
    }
}

Answer: C

join with a timeout waits at most that long and then returns whether or not the thread has died. The worker sleeps for two seconds, so after a hundred milliseconds it is certainly still alive. The difference from the untimed join is that this one does not guarantee termination.

Please log in or register to report this question.

36.

Sample36 is run - what will be the output?

public class Sample36
{
    static class Vault
    {
        synchronized void hold() throws InterruptedException
        {
            Thread.sleep(200);
            System.out.print("held ");
        }

        synchronized void peek() { System.out.print("peeked "); }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Vault v = new Vault();
        Thread a = new Thread(() -> { try { v.hold(); } catch (InterruptedException e) { } });
        a.start();
        Thread.sleep(50);
        v.peek();
        a.join();
    }
}

Answer: D

sleep does not release any monitor, so the worker keeps the lock on the Vault for the whole 200 milliseconds. main wakes after 50 and blocks at peek until the worker has printed and left its synchronized method. Using wait(200) instead would release the lock and reverse the order.

Please log in or register to report this question.

37.

Sample37 is run - what will be the output?

public class Sample37
{
    static class Nested
    {
        synchronized void outer() { System.out.print("outer "); inner(); }

        synchronized void inner() { System.out.print("inner"); }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Thread t = new Thread(() -> new Nested().outer());
        t.start();
        t.join();
    }
}

Answer: A

Java monitors are reentrant, so a thread already holding an object's lock may enter another synchronized method on it; the entry count simply increases. Without that, any such call, including one to a superclass method, would deadlock immediately.

Please log in or register to report this question.

38.

Sample38 is run - what will be the output?

public class Sample38
{
    static final Object A = new Object(), B = new Object();

    public static void main(String[] args)
    {
        new Thread(() ->
        {
            synchronized (A) { sleep(); synchronized (B) { System.out.println("one"); } }
        }).start();
        new Thread(() ->
        {
            synchronized (B) { sleep(); synchronized (A) { System.out.println("two"); } }
        }).start();
    }
}

Answer: B

Each thread takes one lock, pauses long enough for the other to take the second, and then waits for the lock its neighbour holds. Neither can proceed and neither will release, so nothing is printed and the program never ends. Acquiring the two locks in one agreed order everywhere prevents it.

Please log in or register to report this question.

39.

Sample39 is run - what will be the output?

import java.util.concurrent.CountDownLatch;

public class Sample39
{
    public static void main(String[] args) throws InterruptedException
    {
        CountDownLatch ready = new CountDownLatch(2);
        Runnable job = () -> { System.out.print("x"); ready.countDown(); };
        new Thread(job).start();
        new Thread(job).start();
        ready.await();
        System.out.println(" go");
    }
}

Answer: C

await blocks until the count reaches zero, and only the two workers can bring it down, so both have printed before main continues. The two x characters are indistinguishable, so their order does not matter and the output is fully determined.

Please log in or register to report this question.

40.

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

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.

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