I am new to MultiThreading , i am writing an application, In that i have two threads T1 and T2. In T1 i have 15 statements to print, and T2 i have 15 statements to print. I like to wait T2 for some time after T1 executed statement 5 and continue T2 after T1 executes statement 10. I have written the code but T2 is not waiting , can any one please explain.
Thread One : T1
public class ThreadOne extends Thread {
public void run() {
for (int i = 1; i <= 15; i++) {
System.out.println("This is Thread One " + i);
if (i == 5) {
synchronized (Test.threadB) {
try {
Test.threadB.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
} else if (i == 10) {
synchronized (Test.threadB) {
Test.threadB.notify();
}
}
}
}
}
Thread Two : T2
public class ThreadTwo extends Thread {
public void run() {
for (int i = 1; i <= 15; i++) {
System.out.println("This is Thread Two " + i);
}
}
}
Test :
public class Test {
static Thread threadA = null;
static Thread threadB = null;
public static void main(String[] args) throws InterruptedException {
threadA = new ThreadOne();
threadB = new ThreadTwo();
threadA.start();
threadB.start();
}
}
How i expected O/P :
After T1 executed Test.threadB.wait(); when i is 5, no T2 statements has to be printed. after T1 i is 10 , T2 can start printing.
But O/p I am getting is :
This is Thread One 1
This is Thread One 2
This is Thread One 3
This is Thread Two 1
This is Thread Two 2
This is Thread One 4
This is Thread Two 3
This is Thread One 5
This is Thread Two 4
This is Thread Two 5
This is Thread Two 6
This is Thread Two 7
This is Thread Two 8
This is Thread Two 9
This is Thread Two 10
This is Thread Two 11
This is Thread Two 12
This is Thread Two 13
This is Thread Two 14
This is Thread Two 15
This is Thread One 6
This is Thread One 7
This is Thread One 8
This is Thread One 9
This is Thread One 10
This is Thread One 11
This is Thread One 12
This is Thread One 13
This is Thread One 14
This is Thread One 15
Why Only T2 ststements are executing after T1 i==5 or( This is Thread One 5 is printed) ? Please any one explain.