I want to print my odd even number in order 1 2 3 4 5 6. I think first notify call in odd-thread should unblock the even-thread wait() to print next even number but it is not the case. It is printing only "1"
class T1 extends Thread { private String[] s1; private boolean flag; public T1(String[] args, boolean flag) { this.flag = flag; this.s1 = args; } public synchronized void run() { for (int i = 0; i < s1.length; i++) { if(flag) { try { wait(); } catch (InterruptedException e) { System.out.println("exception"); } } System.out.println(s1[i]); notify(); flag = true; } } } public class TestThread { public static void main(String[] args) { String[] s1 = { "1", "3", "5" }; String[] s2 = { "2", "4", "6" }; Runnable odd = new T1(s1,false); Runnable even = new T1(s2,true); new Thread(even,"even-thread ").start(); new Thread(odd,"odd-thread ").start(); } }
Threadobjects, they aren't signaling eachother, they are signaling themselves. Use a shared object. NevernotifyorwaitonThreadinstances.