Multithreading & Concurrency
Difficulty: hard
Overview
Thread states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. Create threads by extending Thread or implementing Runnable. synchronized prevents concurrent access to critical sections. volatile ensures visibility across threads but not atomicity. wait()/notify() for inter-thread communication (defined in Object, called inside synchronized). Deadlock = circular lock dependency. ExecutorService manages thread pools. CountDownLatch is one-time; CyclicBarrier is reusable.
Practice Linked Questions
Q1. A Java Thread can be created by:
Select one answer before revealing.
Q2. The synchronized keyword in Java:
Select one answer before revealing.
Q3. Deadlock in Java multithreading occurs when:
Select one answer before revealing.
Q4. The volatile keyword in Java:
Select one answer before revealing.
Q5. Which of the following are valid Java thread states? (More than one answer may be correct)
Select one answer before revealing.
Q6. The wait() and notify() methods in Java are defined in:
Select one answer before revealing.
Q7. What is the key difference between Thread.sleep() and Object.wait() in Java?
Select one answer before revealing.
Q8. ExecutorService in Java provides:
Select one answer before revealing.
Q9. CountDownLatch in Java:
Select one answer before revealing.
Q10. What is the risk pattern in the following multithreaded code? // Thread 1: synchronized(lockA) { synchronized(lockB) { /* work */ } } // Thread 2: synchronized(lockB) { synchronized(lockA) { /* work */ } }
Select one answer before revealing.
Q11. What does the volatile keyword guarantee in the following scenario? // Shared between threads: volatile boolean running = true; // Thread A: while (running) { doWork(); } // Thread B: running = false;
Select one answer before revealing.
Q12. What is true about the output of the following code? Thread t = new Thread(() -> System.out.println("Thread running")); t.start(); System.out.println("Main done");
Select one answer before revealing.