Multithreading in Java
Multithreading in Java
Key Points:
● Use
Threadclass when you don’t need to extend anyother class.
se
● U Runnablewhen the class needs to extend anotherclass, as Java does not
support multiple inheritance.
start()
Starts the thread.
run()
Entry point for thread execution.
join()
Waits for a thread to finish execution before continuing.
getName()
Returns the thread's name.
etName(String
s Sets the thread's name.
name)
etPriority(int
s Sets the thread priority (1 to 10).
value)
isAlive()
Returns
trueif the thread is still running.
interrupt()
Interrupts the thread if it is sleeping or waiting.
Example:
join()and
sleep()
Java code
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(500); // Pause for 500ms
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
}
hen multiple threads access shared resources, synchronization is needed to prevent data
W
inconsistency.
Synchronization Using
synchronizedKeyword
ynchronized Method:
S
Java code
class SharedResource {
synchronized void printNumbers(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
MyThread(SharedResource resource) {
this.resource = resource;
}
Override
@
public void run() {
resource.printNumbers(5);
}
}
ynchronized Block:
S
Java code
synchronized (object) {
// Critical section
}
6. Deadlock and Its Prevention
● D
eadlock: Occurs when two or more threads are blocked forever, waiting for each
other’s resources.
Example of Deadlock
Java code
lass Resource1 {}
c
class Resource2 {}
t1.start();
t2.start();
}
}
Deadlock Prevention Strategies:
U
● se a consistent lock order.
● Avoid nested locks.
● UsetryLockfromjava.util.concurrent.locks.
ava provides
J ExecutorServicein the
java.util.concurrentpackage to manage
thread pools.
Java code
mport java.util.concurrent.ExecutorService;
i
import java.util.concurrent.Executors;
Callable Example
Java code
mport
i java.util.concurrent.Callable;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Executors;
import
java.util.concurrent.Future;
try {
System.out.println("Waiting for the result...");
Integer result = future.get(); // Blocks until the
result is available
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
}
Key Points:
C
● allable: Similar to
Runnablebut returns a resultand can throw exceptions.
● Future: Represents the result of an asynchronous computation.
CountDownLatch
Java code
import java.util.concurrent.CountDownLatch;
try {
latch.await(); // Wait until count reaches 0
System.out.println("All threads have finished.
Proceeding...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
CyclicBarrier
Used to make threads wait for each other at a common barrier point.
Java code
import java.util.concurrent.CyclicBarrier;
ReentrantLock Example
Java code
mport java.util.concurrent.locks.Lock;
i
import java.util.concurrent.locks.ReentrantLock;
t1.start();
t2.start();
}
}
Key Points:
● ock.lock()
l : Acquires the lock.
● lock.unlock() : Releases the lock.
● Use
try-finallyto ensure proper release of locks.
he Fork/Join framework is designed for parallel execution of tasks. It splits a task into
T
subtasks (fork) and merges the results (join).
Example
Java code
mport java.util.concurrent.RecursiveTask;
i
import java.util.concurrent.ForkJoinPool;
Override
@
protected Integer compute() {
if (end - start <= 2) { // Small enough to compute directly
int sum = 0;
for (int i = start; i < end; i++) {
sum += arr[i];
}
return sum;
} else {
int mid = (start + end) / 2;
SumTask task1 = new SumTask(arr, start, mid);
SumTask task2 = new SumTask(arr, mid, end);
Basics
.
1 hat is a thread, and how is it different from a process?
W
2. What are the main states of a thread in Java?
3. Explain the differences betweenRunnableand Threadclasses.
4. How do you create a thread in Java? Which approach is preferred and why?
. E
5 xplain the lifecycle of a thread with an example.
6. What is the purpose of the join()method in Java?Provide an example.
7. What does the
sleep()method do? How is it differentfrom
wait()?
8. What is
Thread.yield()and when should it be used?
Thread Synchronization
Concurrency Utilities
Common Problems