Working with Multithreading

1. Creating Threads

Example: Thread creation

// Subclass
class Worker extends Thread { public void run() { ... } }
new Worker().start();

// Runnable (preferred)
Thread t = new Thread(() -> doWork(), "worker-1");
t.start();
ApproachDetail
Extend ThreadSingle inheritance limitation
Implement RunnablePreferred — separates task from thread
Implement CallableReturns value, throws checked exception

2. Implementing Runnable Interface

AspectDetail
Methodvoid run()
Functional interfaceUse lambda
ReusablePass to Thread/Executor

3. Implementing Callable Interface

AspectDetail
MethodV call() throws Exception
ReturnsSubmit to executor → Future<V>

4. Understanding Thread Lifecycle

StateTrigger
NEWCreated, not started
RUNNABLEStarted or running
BLOCKEDWaiting for monitor lock
WAITINGwait(), join() w/o timeout
TIMED_WAITINGsleep(), wait(t)
TERMINATEDRun completed

5. Using Thread Methods (start, sleep, join)

MethodDetail
start()Begin execution (call once)
sleep(ms)Static; pauses current thread
join() / join(ms)Wait for thread to finish
yield()Hint to scheduler (advisory)
currentThread()Static; access caller

6. Setting Thread Priority

ConstantValue
MIN_PRIORITY1
NORM_PRIORITY5 (default)
MAX_PRIORITY10
NoteOS-dependent and unreliable

7. Creating Daemon Threads

AspectDetail
Sett.setDaemon(true) before start
BehaviorJVM exits when only daemons remain
UseBackground services, monitoring

8. Interrupting Threads

MethodDetail
interrupt()Signal interruption
isInterrupted()Check (does not clear)
Thread.interrupted()Static; clears flag
Effect on blockingInterruptedException thrown (clears flag)
Warning: Never swallow InterruptedException silently — re-throw or restore via Thread.currentThread().interrupt().

9. Handling InterruptedException

Example: Handle interruption

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();   // restore flag
    return;                                // exit gracefully
}
ApproachUse
Re-throwPropagate up
Restore flagIf can't propagate

10. Setting Thread Names

MethodUse
Constructornew Thread(r, "worker")
setName(s)Change after creation
BenefitEasier debugging in stack traces

11. Using ThreadGroup

AspectDetail
StatusLargely deprecated for management
ReplacementExecutors / structured concurrency

12. Understanding Thread Safety

AspectDetail
DefinitionClass works correctly under concurrent access
StrategiesImmutability, confinement, synchronization, atomics, concurrent collections

13. Identifying Race Conditions

TypeDetail
Read-modify-writee.g., counter++ (not atomic)
Check-then-acte.g., null check before init
DetectionStress tests, JCStress, ThreadSanitizer