17: Multi-threaded Programming
Aim:
To demonstrate a multi-threaded environment. Also demonstrate the usage of sleep() and start()
methods.
Algorithm:
1. Create class MyThread1 extending Thread and override run() to print Thread 1 count 1 to 5
with a 1-second sleep between each iteration
2. Create class MyThread2 extending Thread and override run() to print Thread 2 count 1 to 5
with a 1-second sleep between each iteration
3. Handle InterruptedException inside each run() using a try-catch block
4. In main, create objects t1 and t2 of MyThread1 and MyThread2 respectively
5. Call [Link]() and [Link]() to launch both threads concurrently
Code:
package Chapter1;
class MyThread1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread 1 : " + i);
try {
[Link](1000);
}
catch (InterruptedException e) {
[Link](e);
}
}
}
}
class MyThread2 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread 2 : " + i);
try {
[Link](1000);
}
catch (InterruptedException e) {
[Link](e);
}
}
}
}
public class MultiThreadDemo {
public static void main(String[] args) {
[Link]("Name: Chinmayi Gururaj C");
[Link]("USN: 2112408011");
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
[Link]();
[Link]();
}
}
Output:
Result:
A multi-threaded environment was demonstrated successfully using two threads running
concurrently, with the sleep() method used to introduce a delay between iterations.
Date of Performance Date of Evaluation Faculty signature Remarks