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

Threads - Finding the output Questions and Answers

61.

Sample61 is run - what will be the output?

public class Sample61
{
    public static void main(String[] args)
    {
        final Object lock = new Object();
        System.out.print(Thread.holdsLock(lock) + " ");
        synchronized (lock)
        {
            System.out.print(Thread.holdsLock(lock));
        }
    }
}

Answer: A

holdsLock reports whether the current thread owns the monitor of the given object at that moment. Outside the synchronized block it does not, and inside it does. The method exists for assertions and diagnostics rather than for control flow.

Please log in or register to report this question.

62.

Sample62 is run - what will be the output?

public class Sample62
{
    static int shared = 0;

    static class Job implements Runnable
    {
        int local = 0;

        public void run()
        {
            for (int i = 0; i < 3; i++) { local++; shared++; }
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Job job = new Job();
        Thread a = new Thread(job), b = new Thread(job);
        a.start(); a.join(); b.start(); b.join();
        System.out.println(job.local + " " + shared);
    }
}

Answer: B

Both threads run the same Job instance, so its field is shared just as the static one is; nothing is copied per thread. Each thread adds three to both, giving six each. Starting the second thread only after joining the first removes any interleaving, so the totals are exact.

Please log in or register to report this question.

63.

Sample63 is run - what will be the output?

public class Sample63
{
    static class Broken
    {
        Broken()
        {
            new Thread(() -> System.out.println(value)).start();
            value = 42;
        }

        int value;
    }

    public static void main(String[] args) throws InterruptedException
    {
        new Broken();
        Thread.sleep(200);
    }
}

Answer: C

Starting a thread from inside the constructor publishes this before the object is finished, so the new thread may observe the field at its default value or at 42 depending on timing. Publishing a reference only after construction has completed is what avoids the race.

Please log in or register to report this question.

64.

Sample64 is run - what will be the output?

public class Sample64
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread low = new Thread(() -> System.out.print("L"));
        Thread high = new Thread(() -> System.out.print("H"));
        low.setPriority(Thread.MIN_PRIORITY);
        high.setPriority(Thread.MAX_PRIORITY);
        low.start(); high.start();
        low.join(); high.join();
    }
}

Answer: D

Priority is a hint to the platform's scheduler and its effect varies between JVMs and operating systems, so neither ordering is promised. 1 and 10 are legal values, so nothing is thrown. Real ordering needs join between the two starts, a lock or a latch.

Please log in or register to report this question.

65.

Sample65 is run - what will be the output?

public class Sample65
{
    static final Runnable POLITE = () ->
    {
        for (int spin = 0; spin < 3; spin++)
        {
            Thread.yield();
        }
        System.out.print("worker");
    };

    public static void main(String[] args) throws InterruptedException
    {
        Thread courteous = new Thread(POLITE);
        courteous.start();
        courteous.join();
        System.out.print(" main");
    }
}

Answer: A

yield is only a hint that the scheduler may ignore, and it never ends a thread or transfers control to a named one, however many times it is called. Whatever it does or does not do, the join still guarantees the worker finishes before main's print, so the order is fixed by the join alone.

Please log in or register to report this question.

66.

Sample66 is run - what will be the output?

public class Sample66
{
    public static void main(String[] args) throws InterruptedException
    {
        long start = System.currentTimeMillis();
        Thread.sleep(0);
        System.out.println(System.currentTimeMillis() - start < 100);
    }
}

Answer: B

Correct answer: true

Thread.sleep(0) is legal and returns essentially at once - it is at most a hint to the scheduler that the thread is willing to yield. The elapsed time is therefore a millisecond or two and the comparison prints true. Only a *negative* argument throws IllegalArgumentException.

Please log in or register to report this question.

67.

Sample67 is run - what will be the output?

import java.util.concurrent.Semaphore;

public class Sample67
{
    public static void main(String[] args) throws InterruptedException
    {
        Semaphore permits = new Semaphore(1);
        permits.acquire();
        System.out.print(permits.availablePermits() + " ");
        permits.release();
        System.out.print(permits.availablePermits());
    }
}

Answer: C

acquire takes a permit and blocks if none is available, so the count drops to zero; release returns one, taking it back to one. A semaphore counts rather than tracking an owner, which is why release may be called by a thread that never acquired.

Please log in or register to report this question.

68.

Sample68 is run - what will be the output?

import java.util.*;
import java.util.concurrent.*;

public class Sample68
{
    public static void main(String[] args) throws Exception
    {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Callable<String>> jobs = Arrays.asList(() -> "a", () -> "b");
        List<Future<String>> done = pool.invokeAll(jobs);
        for (Future<String> f : done) System.out.print(f.get());
        pool.shutdown();
    }
}

Answer: D

invokeAll returns only when every task has completed, and the list of futures comes back in the same order as the tasks were supplied, whatever order they actually ran in. So iterating the list gives a and then b deterministically.

Please log in or register to report this question.

69.

Sample69 is run - what will be the output?

import java.util.concurrent.atomic.AtomicInteger;

public class Sample69
{
    public static void main(String[] args)
    {
        AtomicInteger n = new AtomicInteger(5);
        System.out.print(n.compareAndSet(5, 9) + " ");
        System.out.print(n.compareAndSet(5, 12) + " ");
        System.out.print(n.get());
    }
}

Answer: A

The first call finds the expected 5 and writes 9, reporting success. The second still expects 5, but the value is now 9, so it writes nothing and returns false. The final value is therefore 9, and the boolean result is what lets a retry loop work without a lock.

Please log in or register to report this question.

70.

Sample70 is run - what will be the output?

import java.util.*;

public class Sample70
{
    public static void main(String[] args) throws InterruptedException
    {
        List<Integer> list = Collections.synchronizedList(new ArrayList<>());
        Runnable job = () -> { for (int i = 0; i < 500; i++) list.add(i); };
        Thread a = new Thread(job), b = new Thread(job);
        a.start(); b.start(); a.join(); b.join();
        System.out.println(list.size());
    }
}

Answer: B

Each add is individually synchronized, and a list keeps duplicates, so all 1000 additions land and the size is exact. What the wrapper does not make atomic is a sequence of calls, so iterating or a check-then-add would still need the caller to hold the lock.

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