I need to make a program that runs two threads. One that outputs ping and sleeps for ten second and one that outputs pong and sleeps for ten seconds. Everything works except instead of sleeping for ten seconds everytime the thread is ran its just jumps to the second thread THEN waits ten seconds. If you could explain why it does that i would appreciate it. Thank You.
public class PingPong implements Runnable{
private boolean tchoice; //Will hold the choice to display ping or pong
public PingPong(boolean choice)
{
tchoice = choice; //Sets the choice to tchoice
}
@Override
public void run() //Implemented Runnable method
{
//if tchoice is true display ping
if(tchoice)
ping();
//if not display pong
else
pong();
}
//This method displays ping
private void ping()
{
try
{
for(int counter = 0; counter < 5; counter++)
{
System.out.println("ping");
Thread.sleep(10000); //Thread sleeps for 10 seconds
}
}
catch(InterruptedException e)
{
System.err.println("Thread Interrupted");
}
}
//This method displays pong
private void pong()
{
try
{
for(int counter = 0; counter < 5; counter++)
{
System.out.println("pong");
Thread.sleep(10000); //Thread sleeps for 10 seconds
}
}
catch(InterruptedException e)
{
System.err.println("Thread Interrupted");
}
}
}
public class ThreadsMain {
public static void main(String args[])
{
Thread thread = new Thread(new PingPong(true)); //Creates a thread with the thread that creates ping
Thread thread1 = new Thread(new PingPong(false)); //Creates a therad with the trhead that creates pong
//displays ping and pong 10 time
thread1.start();
thread.start();
}
}