Threads & Concurrency Basics Questions with Answers

23 practice questions on Threads & Concurrency Basics (Core Java) with answers and step-by-step solutions. Try 10 samples below, then practise all 23 free in the AptiNest app.

Sample questions

Question 1Easy

What is the output?

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(() -> System.out.print(Thread.currentThread().getName() + " "), "worker");
        t.run();
        System.out.println(Thread.currentThread().getName());
    }
}
  1. main main
  2. worker main
  3. main worker
  4. worker worker

Answer: A. main main

Explanation

Calling run() directly is an ordinary method call on the current thread, so currentThread() is main both times; only start() creates a new thread.

Step-by-step solution

  1. t.run() calls the lambda directly on the main thread.
  2. getName() is main, so it prints 'main '.
  3. Then main is printed.

Why the other options are wrong

  • B. The thread was never started, so 'worker' is not used.
  • C. run() executes inline in main.
  • D. No new thread exists.

Tip: start() for a thread, run() is just a call.

Question 2Easy

What does the volatile keyword guarantee for a field?

  1. Every read sees the most recent write by any thread (visibility and ordering)
  2. Compound actions like count++ become atomic
  3. Only one thread can access the field at a time
  4. The field is stored on the thread stack instead of the heap

Answer: A. Every read sees the most recent write by any thread (visibility and ordering)

Explanation

volatile provides visibility and happens-before ordering, but it does not make read-modify-write operations such as ++ atomic; use synchronized or AtomicInteger for that.

Step-by-step solution

  1. volatile ensures visibility and ordering.
  2. It does not make count++ atomic.
  3. So option A is correct.

Why the other options are wrong

  • B. Atomicity needs synchronized or AtomicInteger.
  • C. That is mutual exclusion.
  • D. Volatile fields stay on the heap.

Tip: volatile = visibility only.

Question 3Easy

Which two ways are standard for defining the task a new Thread will execute?

  1. Override start() in a subclass, or implement Cloneable
  2. Override main() in a subclass, or implement Comparable
  3. Extend Thread and override run(), or pass a Runnable to the Thread constructor
  4. Implement Serializable, or call Thread.execute()

Answer: C. Extend Thread and override run(), or pass a Runnable to the Thread constructor

Explanation

The thread body is run(): either a Thread subclass overrides it or a Runnable (often a lambda) supplies it; start() should not be overridden.

Step-by-step solution

  1. The task a thread runs is its run() method.
  2. Way one: extend Thread and override run().
  3. Way two: pass a Runnable, often a lambda, to the Thread constructor.
  4. The answer is option C.

Why the other options are wrong

  • A. start() should not be overridden to define the task, and Cloneable is unrelated.
  • B. main() is not the thread body, and Comparable is unrelated to threads.
  • D. Serializable is unrelated, and Thread has no execute() method.

Tip: Define the work in run(); call start() to run it on a new thread.

Question 4Easy

What is the output?

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

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService ex = Executors.newSingleThreadExecutor();
        Future<Integer> f = ex.submit(() -> 6 * 7);
        System.out.println(f.get());
        ex.shutdown();
    }
}
  1. 42
  2. Future[42]
  3. Compilation error
  4. null

Answer: A. 42

Explanation

submit with a value-returning lambda treats it as a Callable<Integer>; Future.get() blocks until the task finishes and returns 42.

Step-by-step solution

  1. The lambda () -> 6 * 7 returns an Integer value of 42.
  2. f.get() retrieves the result of the submitted task, which is 42.
  3. System.out.println prints the retrieved value, which is 42.
  4. The program completes successfully without errors.
  5. The output displayed is 42.

Why the other options are wrong

  • B. f.get() returns the task's value, 42, not the Future object's toString.
  • C. The Callable lambda returning an Integer compiles and submit accepts it, so there is no error.
  • D. The task returns 6 * 7 = 42, and get() returns that value, not null.

Tip: Remember, submit() with a lambda that returns a value behaves like a Callable.

Question 5Medium

What is the output?

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

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService ex = Executors.newFixedThreadPool(2);
        Future<Integer> f = ex.submit(() -> { if (true) throw new IllegalStateException("x"); return 1; });
        try {
            f.get();
        } catch (ExecutionException e) {
            System.out.println("EE " + e.getCause().getClass().getSimpleName());
        }
        ex.shutdown();
    }
}
  1. EE ExecutionException
  2. EE IllegalStateException
  3. 1
  4. IllegalStateException

Answer: B. EE IllegalStateException

Explanation

An exception thrown inside a Callable is captured by the Future; get() wraps it in an ExecutionException whose cause is the original exception.

Step-by-step solution

  1. The task is a Callable that throws IllegalStateException with the message x.
  2. The Future catches the exception instead of letting it crash the pool.
  3. f.get() throws ExecutionException, whose cause is the original IllegalStateException.
  4. The catch block prints EE IllegalStateException, which is option B.

Why the other options are wrong

  • A. The exception is ExecutionException, but getCause() returns the original IllegalStateException.
  • C. The task throws before it returns, so the value 1 is never produced.
  • D. get() throws ExecutionException, and the catch block prints the EE text first.

Tip: Future.get() wraps any task exception in ExecutionException; call getCause() to see the original one.

Question 6Medium

What is the output?

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

public class Main {
    public static void main(String[] args) {
        Object lock = new Object();
        lock.notify();
    }
}
  1. Compilation error
  2. InterruptedException is thrown
  3. Nothing happens because no thread is waiting
  4. IllegalMonitorStateException is thrown

Answer: D. IllegalMonitorStateException is thrown

Explanation

notify(), notifyAll() and wait() require the calling thread to own the object's monitor (be inside synchronized(lock)); otherwise IllegalMonitorStateException is thrown.

Step-by-step solution

  1. lock.notify() calls notify without holding the lock's monitor.
  2. notify() requires the thread to own the object's monitor; otherwise, IllegalMonitorStateException is thrown.
  3. Since no thread is in synchronized block, IllegalMonitorStateException occurs.
  4. The code lacks synchronized context for lock, leading to exception.
  5. Thus, IllegalMonitorStateException is thrown at runtime.
  6. Final answer: IllegalMonitorStateException is thrown.

Why the other options are wrong

  • A. notify() is a valid Object method and compiles fine; the failure happens at runtime.
  • B. InterruptedException comes from waiting or sleeping threads, not from notify on a lock not held.
  • C. notify without owning the monitor throws even when no thread is waiting; the check comes first.

Tip: Always use synchronized blocks with notify()/wait() to avoid IllegalMonitorStateException.

Question 7Medium

What happens to a running daemon thread when all non-daemon (user) threads in the JVM have finished?

  1. The JVM exits without waiting for it to finish
  2. It is converted to a user thread and continues
  3. The JVM waits until it completes
  4. It throws InterruptedException and then finishes normally

Answer: A. The JVM exits without waiting for it to finish

Explanation

The JVM keeps running only while user threads are alive; daemon threads (such as the GC) are abandoned when the last user thread ends.

Step-by-step solution

  1. Daemon threads run in background.
  2. JVM exits when all non-daemon threads finish.
  3. Daemon threads are not waited on.
  4. So JVM exits without waiting for daemon thread to finish.
  5. Final answer: The JVM exits without waiting for it to finish.

Why the other options are wrong

  • B. A daemon thread is never converted; the JVM simply exits once only daemon threads remain.
  • C. The JVM does not wait for daemon threads; only non-daemon threads keep it alive.
  • D. The JVM does not interrupt daemon threads, so no InterruptedException is thrown; the thread is just stopped.

Tip: Remember: JVM exits when user threads end, ignoring daemon threads.

Question 8Medium

What is the output?

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {});
        t.start();
        t.start();
    }
}
  1. Compilation error
  2. The second start() is silently ignored
  3. IllegalThreadStateException is thrown
  4. The thread runs twice

Answer: C. IllegalThreadStateException is thrown

Explanation

A Thread object can be started only once; calling start() again throws IllegalThreadStateException.

Step-by-step solution

  1. A thread can be started only once.
  2. Second start() throws IllegalThreadStateException.

Why the other options are wrong

  • A. The code compiles.
  • B. It is not ignored.
  • D. The thread cannot run twice.

Tip: One start per Thread object.

Question 9Hard

What is the output?

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

public class Main {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(() -> {
            try {
                Thread.sleep(10_000);
                System.out.println("woke");
            } catch (InterruptedException e) {
                System.out.println("interrupted " + Thread.currentThread().isInterrupted());
            }
        });
        t.start();
        t.interrupt();
        t.join();
    }
}
  1. interrupted true
  2. Nothing is printed
  3. woke
  4. interrupted false

Answer: D. interrupted false

Explanation

interrupt() makes sleep() throw InterruptedException (immediately, or as soon as sleep starts if the flag is already set); throwing it clears the interrupt flag, so isInterrupted() is false.

Step-by-step solution

  1. The thread calls sleep(10_000), which would wait 10 seconds.
  2. interrupt() is called right after start(), so sleep() throws InterruptedException, at once if the flag is already set.
  3. Throwing InterruptedException clears the interrupt flag, so isInterrupted() returns false.
  4. Output: interrupted false, which is option D.

Why the other options are wrong

  • A. The flag is cleared when InterruptedException is thrown, so isInterrupted() is false.
  • B. The interrupt wakes the sleeping thread, so the catch block does print a line.
  • C. The sleep is cut short by the interrupt, so woke is never printed.

Tip: Catching InterruptedException clears the interrupt status; restore it with Thread.currentThread().interrupt() if needed.

Question 10Hard

What is the output?

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

public class Main {
    public static void main(String[] args) throws Exception {
        ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<>();
        ExecutorService ex = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 1000; i++) ex.submit(() -> m.merge("k", 1, Integer::sum));
        ex.shutdown();
        ex.awaitTermination(10, TimeUnit.SECONDS);
        System.out.println(m.get("k"));
    }
}
  1. 1000
  2. 4
  3. A value below 1000 that varies between runs
  4. 1

Answer: A. 1000

Explanation

ConcurrentHashMap.merge is atomic per key, and awaitTermination waits for all submitted tasks, so all 1000 increments are counted.

Step-by-step solution

  1. The 1000 tasks each call merge on key k, adding 1 to its value.
  2. merge() is atomic for each key, so no increment is lost.
  3. shutdown() stops new tasks from being accepted, and awaitTermination() waits (up to 10 seconds) for all 1000 tasks to finish before the value is read.
  4. Output: 1000, which is option A.

Why the other options are wrong

  • B. 4 is the number of threads in the pool, not the counter value.
  • C. merge() is atomic, so the count is exact every time and does not vary.
  • D. Each task adds 1, so the total is 1000, not 1.

Tip: ConcurrentHashMap.merge() is an atomic read-modify-write, so it is safe to call from many threads.

Practise all 23 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Core Java topics · All topics