I am new to threads and I can't seem to synchronize them properly. I want my program's output to be:
Hi
Bye
Hi
Bye
etc.
Instead of that output though I always get:
Hi
Hi
Bye
Hi
Hi
Bye
Hi
Hi
Hi
Bye
Hi
Hi
Hi
Bye
I can't understand why the byeThread won't finish properly, as it is supposed to loop 10 times but only does it 4 times.
public class
Word extends
Thread {
public synchronized void sayHi()
throws InterruptedException
{
System.out.println("Hi");
sleep(500);
notify();
}
public synchronized void sayBye()
throws InterruptedException
{
wait();
sleep(500);
System.out.println("Bye");
}
}
///////////////////////////////////////////////////////////////////////
public class hiThread extends Thread
{
public Word a;
public hiThread(Word w)
{
a = w;
}
public void run()
{
try
{
for (int x=0; x < 10; x++)
{
a.sayHi();
}
}
catch (Exception e)
{
}
}
}
///////////////////////////////////////////////////////////////////////
public class byeThread extends Thread
{
public Word a;
public byeThread(Word w)
{
a =w;
}
public void run()
{
try
{
for (int x=0; x < 10; x++)
{
a.sayBye();
}
}
catch (Exception e)
{
}
}
}
/////////////////////////////////////////////////////////////////
public class Go
{
public static void main(
String[] args)
{
Word myWord = new Word();
hiThread B = new hiThread(myWord);
byeThread C = new byeThread(myWord);
B.start();
C.start();
}
}