Java program on Multithearding by extending Thread Class Example 5
PROGRAM:
class Counter extends Thread {Counter() {
System.out.println("Constructor (o_o)");
System.out.println("Thread created " + this);
start();
}
public void run() {
try {
for (int i = 1; i <= 10; i++) {
sleep(1000);
System.out.println("Hello I'm Thread (-_-) count" + i);
}
} catch (InterruptedException e) {
System.out.println("my thread interrupted");
}
}
}
public class ThreadingDemo5 {
public static void main(String[] args) {
Counter c = new Counter();
try {
while (c.isAlive()) {
System.out.println("Thread is alive");
Thread.sleep(2000);
}
} catch (InterruptedException i) {
System.out.println("Thread interrupted");
}
}
}
OUTPUT:
Constructor (o_o)Thread created Thread[Thread-0,5,main]
Thread is alive
Hello I'm Thread (-_-) count1
Thread is alive
Hello I'm Thread (-_-) count2
Hello I'm Thread (-_-) count3
Thread is alive
Hello I'm Thread (-_-) count4
Hello I'm Thread (-_-) count5
Thread is alive
Hello I'm Thread (-_-) count6
Hello I'm Thread (-_-) count7
Thread is alive
Hello I'm Thread (-_-) count8
Hello I'm Thread (-_-) count9
Thread is alive
Hello I'm Thread (-_-) count10