Java Program on Multithreading by extending Thread class Example 4
THREAD:
A thread is a light-weight smallest part of a process that can run concurrently with the other threads of the same process. All threads of a process share the common memory.MULTITHREADING:
The process of executing multiple threads simultaneously is known as multithreading.
PROGRAM:
class MyThread1 extends Thread {
public void run() {
try {
for (int i = 1; i <= 10; i++) {
sleep(500);
System.out.println("Hello I'm Thread " + i + " (-_-)");
}
} catch (InterruptedException e) {
System.out.println("my thread interrupted");
}
}
}
class MyThread2 extends Thread {
public void run() {
try {
for (char i = 'a'; i <= 'j'; i++) {
sleep(1000);
System.out.println("Hi I'm Thread " + i + " (*_*)");
}
} catch (InterruptedException e) {
System.out.println("my thread interrupted");
}
}
}
class ThreadingDemo2 {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}
public void run() {
try {
for (int i = 1; i <= 10; i++) {
sleep(500);
System.out.println("Hello I'm Thread " + i + " (-_-)");
}
} catch (InterruptedException e) {
System.out.println("my thread interrupted");
}
}
}
class MyThread2 extends Thread {
public void run() {
try {
for (char i = 'a'; i <= 'j'; i++) {
sleep(1000);
System.out.println("Hi I'm Thread " + i + " (*_*)");
}
} catch (InterruptedException e) {
System.out.println("my thread interrupted");
}
}
}
class ThreadingDemo2 {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}
OUTPUT:
Hello I'm Thread 1 (-_-)Hi I'm Thread a (*_*)
Hello I'm Thread 2 (-_-)
Hello I'm Thread 3 (-_-)
Hi I'm Thread b (*_*)
Hello I'm Thread 4 (-_-)
Hello I'm Thread 5 (-_-)
Hi I'm Thread c (*_*)
Hello I'm Thread 6 (-_-)
Hello I'm Thread 7 (-_-)
Hi I'm Thread d (*_*)
Hello I'm Thread 8 (-_-)
Hello I'm Thread 9 (-_-)
Hi I'm Thread e (*_*)
Hello I'm Thread 10 (-_-)
Hi I'm Thread f (*_*)
Hi I'm Thread g (*_*)
Hi I'm Thread h (*_*)
Hi I'm Thread i (*_*)
Hi I'm Thread j (*_*)