Entrance Exams
Govt. Exams
The Runnable interface contains a single run() method that defines the code to be executed when a thread runs. It's preferred over extending Thread class.
Java's monitors are reentrant. A thread can acquire the same lock multiple times. An internal counter tracks lock acquisitions and releases.
Context switching is the OS mechanism of switching CPU execution between different threads, saving and restoring thread state.
CountDownLatch is used for one-time synchronization where threads wait for a countdown to reach zero. CyclicBarrier can be reused after threads are released.
CyclicBarrier allows multiple threads to wait for each other at a specific point. CountDownLatch is for one-time synchronization; CyclicBarrier is reusable.
java
synchronized void method1() { method2(); }
synchronized void method2() { }
Java's intrinsic locks are reentrant, meaning the same thread can acquire the same lock multiple times. The thread can call method2() from method1() without deadlock.
ExecutorService manages a pool of threads, reusing them for multiple tasks, which reduces overhead and improves resource utilization.
Synchronized methods automatically acquire and release the monitor lock (intrinsic lock) associated with the object, ensuring thread safety.
The getState() method returns the Thread.State enum indicating whether a thread is NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED.
interrupt() sets the interrupt status flag. If the thread is not waiting or sleeping, it continues execution but the status is marked as interrupted.