public class CreateThreadRunnableExample implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Child Thread : " + i);
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Child thread finished!");
}
public static void main(String[] args) {
Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");
t.start();
for (int i = 0; i < 5; i++) {
System.out.println("Main thread : " + i);
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Main thread finished!");
}
}
in this program two sleep methods are used of deifferent time..,,, so if main thread run time then child thread have to run 2 time.but it runs one time only....it we take the concept of runnable or running state....then when main thread end,then 2 child threads will be in ready state then why only one child thread runs.
First of all you have added System.out.println("Child thread interrupted! " + ie); for both the main and the child thread, thats a typo...
Try this... Both the threads are running (Main and the Child thread)
Main method of this program is put on to the bottom of the Main thread created by JVM, and the Main method creates another Runtime Stack and puts the child thread in it.
public class DemoThread implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Child Thread ");
try {
Thread.sleep(200);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Child thread finished!");
}
public static void main(String[] args) {
Thread t = new Thread(new DemoThread ());
t.start();
for (int i = 0; i < 3; i++) {
System.out.println("Main thread);
try {
Thread.sleep(200);
} catch (InterruptedException ie) {
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Main thread finished!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With