I am working in core java. I have one small program which will print numbers 1,2,3 by corresponding threads thread1 , thread2 and thread3.
while(true)
{
synchronized (obj)
{
System.out.println("Thread got chance : "+Thread.currentThread().getName());
if (ai.get() ==0 && Thread.currentThread().getName().equalsIgnoreCase("Thread1"))
{
System.out.print(ai.incrementAndGet()+"("+Thread.currentThread().getName()+")"+" ");
obj.notify();
obj.wait();
}
if (ai.get() ==1 && Thread.currentThread().getName().equalsIgnoreCase("Thread2"))
{
System.out.print(ai.incrementAndGet()+"("+Thread.currentThread().getName()+")"+" ");
obj.notify();
obj.wait();
}
if (ai.get() ==2 && Thread.currentThread().getName().equalsIgnoreCase("Thread3"))
{
System.out.print(ai.incrementAndGet()+"("+Thread.currentThread().getName()+")"+" ");
System.out.println("");
ai.set(0);
obj.notify();
obj.wait();
}
}
}
in the above program logic is fine and working i.e it is printing in order. But I have printed the thread name with "Thread got change ". i.e I was trying to identify which thread is getting more chance to run and got to know the thread name Ex thread 2.
The question is "How I can make sure that, all the threads are getting same chances. Since this is the small program , thread will do its work and come out within milliseconds and we will not come to know. What if a thread takes little long time to run" ?
Please help.