Govt Exams
A thread can only exist in one state at a time (NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED). Calling start() multiple times throws IllegalThreadStateException. The start() method should be called, not run() directly.
Atomic variables use Compare-And-Swap (CAS) operations for lock-free thread safety, providing better performance in high-concurrency scenarios compared to traditional locking.
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.