Java Module5 All Answers
Java Module5 All Answers
A thread is a lightweight sub-process, the smallest unit of processing. Threads allow multitasking in
Java.
Advantages:
1. Multitasking
2. Resource sharing
3. Faster execution
5. Improves performance
Example:
System.out.println("Thread is running...");
t.start();
Q2: How do you create a thread in Java using the Thread class?
Example:
t.start();
Benefits:
- Faster execution
Example:
class Counter {
int count = 0;
count++;
}
Q6: What is a thread pool in Java?
Example:
service.shutdown();
Example:
System.out.println("Runnable running...");
t.start();
Example:
System.out.println("Running...");
t.start();
System.out.println("Main ends");
Q9: How does the wait() and notify() method work in Java?
Example:
synchronized(obj) {
Deadlock is when two threads wait for each other to release resources and never proceed.
States: New -> Runnable -> Running -> (Waiting/Blocked) -> Terminated
Example:
ExecutorService ex = Executors.newFixedThreadPool(2);
ex.execute(task); ex.shutdown();
Example:
f.get();
Each example demonstrates different ways to create and run threads in Java.
1. synchronized method
2. synchronized block
Use ExecutorService, avoid Thread.sleep, prefer concurrent utilities, minimize shared data.