Govt. Exams
Entrance Exams
CountDownLatch is designed for one-time barrier scenarios where threads wait for a countdown to reach zero. With an initial count of 5, it perfectly suits this use case. Semaphore is reusable, Phaser handles multiple phases, and Mutex is not a Java class.
The wait() method causes a thread to release all acquired locks and enter a waiting state until notify() or notifyAll() is called. sleep(), yield(), and join() do not release locks.
Java thread states are: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. SUSPENDED is not a valid state in Java's threading model.
start() creates a new thread and calls run() in that new thread, while directly calling run() executes it in the current thread without creating a new thread.
The run() method must be implemented when creating a thread either by extending Thread class or implementing Runnable interface. The start() method calls run() internally.
Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()));
t.start();
When a new Thread is created without a name parameter, it gets a default name 'Thread-n' where n is a counter. The thread will print 'Thread-0' as it is the first thread created.
ConcurrentHashMap is designed for concurrent access without requiring external synchronization. HashMap and others are not thread-safe.
The synchronized keyword creates a critical section that only one thread can access at a time, preventing race conditions. volatile ensures visibility but not atomicity.
ConcurrentHashMap uses segment-based locking (in older versions) or fine-grained locking to provide thread-safety without synchronizing the entire map. Other options require external synchronization or Collections.synchronizedMap().
Deadlock occurs when two or more threads are waiting indefinitely for locks held by each other. Option B creates a reentrant situation (allowed in ReentrantLock). Option C is problematic but not necessarily deadlock. Option D is safe if used properly.