Experiment-9 OOPS
Experiment-9 OOPS
EXPERIMENT-9
Aim: Design a program to demonstrate multi-threading using Thread Class.
Theory:
IIOT RAGHAV JINDAL 00417711723
Program:
1. Using Inheritance:
// Class that demonstrates multi-threading
public class MultiThreadExample {
// Thread class for printing numbers
static class PrintNumbersThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
// Thread class for printing letters
static class PrintLettersThread extends Thread {
public void run() {
for (char c = 'A'; c <= 'E'; c++) {
System.out.println("Letter: " + c);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
IIOT RAGHAV JINDAL 00417711723
}
}
}
try {
// Wait for both threads to finish
numbersThread.join();
lettersThread.join();
} catch (InterruptedException e) {
System.out.println(e);
}
2. Using Interfaces
// Class that demonstrates multi-threading using Runnable interface
public class MultiThreadUsingRunnable {
// Runnable class for printing numbers
IIOT RAGHAV JINDAL 00417711723
try {
// Wait for both threads to finish
numbersThread.join();
lettersThread.join();
} catch (InterruptedException e) {
System.out.println(e);
}
1. Using Inheritance:
IIOT RAGHAV JINDAL 00417711723
2. Using Interfaces
IIOT RAGHAV JINDAL 00417711723
Output:
Learning Outcome: