Java Program to Demonstrate Multi-Threading (10 Marks)
Multithreading in Java:
Multithreading is a process of executing multiple threads simultaneously to achieve parallelism.
A thread is the smallest unit of a process. Java supports multithreading through the Thread class and
Runnable interface.
Need for Multithreading:
1. Efficient utilization of CPU.
2. Faster execution of tasks.
3. Helps in creating interactive applications.
4. Enables concurrent execution of independent tasks.
Methods of Thread Class:
1. start() – starts the execution of a thread.
2. run() – contains the code that will run in the thread.
3. sleep(ms) – pauses execution for given milliseconds.
4. getName() – returns the thread's name.
5. setName() – assigns a name to the thread.
6. join() – waits for a thread to finish execution.
Creating Threads:
There are two ways:
1. Extending Thread class
2. Implementing Runnable interface
Below is a program demonstrating multithreading using Thread class.
Java Code:
// Java Program to Demonstrate Multi-Threading (10 Marks)
class Worker extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " executing: " + i);
try {
[Link](500); // Pause for 0.5 seconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
public class MultiThreadDemo {
public static void main(String[] args) {
Worker t1 = new Worker();
Worker t2 = new Worker();
[Link]("Worker-1");
[Link]("Worker-2");
[Link](); // Start first thread
[Link](); // Start second thread
}
}