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();




    }

}

Edited 4 Years Ago by devninja

I wouild expect that to print "ping" and "pong" (or "pong" and "ping"), then wait 10 secs, and repeat.
What does yours do? How exactly does that differ from what you expect?

hmm try using swing timers for that as you can run a scheduled timer to go off every 10 seonds. The reason your threads are giving you that output is because its what threads are used for. Hence it will work on one thread until that thread is paused or interrupted then swicth through to your other thread.

@JamesCherrill it outputs ping or pong in what ever order the thread is executed but it only sleeps for ten seconds after ping and ping were both printed although I have it where it should sleep everytime ping or pong are printed.

That's correct behaviour. You start two threads (almost) simultaneously. Each prints a word then waits. So you should see both words printed, both threads wait, both threads print etc

thats the problem it prints two words then waits insteand of printing a word waintin then printing another word and waiting and so on.

What timing of the printlns are you trying to achieve?

Each thread is independent of the other. If you want them to coordinate when they print, you will have to change the code so that when one prints it starts the other one to do its wait. And so forth.

Why not use a Timer that calls its listener every 10 seconds?

Is this how you want the threads to work:
T1 print @10 @30 @50 @70
T2 print @20 @40 @60 @80

Edited 4 Years Ago by NormR1

T1 waits 10 sec first time and then 20 sec every time after that
T2 waits 20 sec every time

But that causes them to be in synch and print at the same time every 10 seconds.

T2 print @20 @40 @60 @80

Look at the above. T2 prints every 20 seconds. If that is what you want, then T2 needs to sleep for 20 sec between doing a print.

look at the code i posted i have it sleep everytime it prints somthing. line 29 and 46. I'm not using a timer. I'm using Thread.sleep()

Look at when T1 & T2 should print. It's every 20 sec. You need to sleep 20 seconds between each print.

I have it print every 10 seconds based. And i have Thread.sleep() after each print

All the threads in your code print at a 10 sec interval. If there were 100 threads, they would all print at the same time every 10 secs.

Edited 4 Years Ago by NormR1

That's the way threads work. Their purpose is to do things in parallel/at the same time with other threads. With a multi-core CPU different threads can truly do things at the same time with each thread executing at the same time on its own core.

Your threads do their waiting at the same time, The same 10 secs of wall clock time.

Edited 4 Years Ago by NormR1

Each thread does wait 10 seconds between prints.
If you want one thread to wait 10secs after the other has printed, then you will have to have them coordinate with each other. When one prints it should tell the other: wait 10 sec and print
There are probably several ways to do that.
Look at the join method(not sure how this would work) or ar the Object class's wait and notify methods

Edited 4 Years Ago by NormR1

it still does the same thing. I syncrozied run() and used wait() and notifyAll() instead of Thread.sleep but it still prints ping and pong then waits ten seconds

Does the code wait and notify? Add some printlns that shows when a thread calls wait and when it returns from wait() . Use the System.currentTImeMillis() method to record the time when all events happen. You still need to call sleep if you want a thread to wait 10 secs.

Post the new code.

I think it just does that because I have a multicore cpu

No, threading works in very similar ways regardless of number of cores. It's doing the wrong thing because your code is wrong. If you don't post your code nobody can help.

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 synchronized void run() //Implemented Runnable method
    {
        //if tchoice is true display ping


        try
        {

            if(tchoice)
            {
                for(int counter = 0; counter < 5; counter++)
                {
                    ping();
                    wait(10000);
                    //Thread.sleep(10000); //Thread sleeps for 10 seconds
                    notifyAll();
                }
            }
            //if not display pong
            else
            {
                for(int counter = 0; counter < 5; counter++)
                {
                    pong();
                    wait(10000);
                    //Thread.sleep(10000); //Thread sleeps for 10 seconds
                    notifyAll();
                }
            }
        }
        catch(InterruptedException e)
        {

        }

    }




    //This method displays ping
    private void ping() 
    {

        System.out.println("ping");


    }

    //This method displays pong
    private void pong()
    {
        System.out.println("pong");
    }


}



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 thread with the thread that creates pong

        //displays ping and pong 10 time 
        thread.start();
        thread1.start();





    }

}

How do your threads tell each other went to start? They are started independently of each other and run in parallel without any need to know about the other. Your wait and notify are not sharing an object between the two threads and are completely independent in each thread.

The code would be simpler if you passed the ping/pong as a parameter to the class and just print it as the message instead of the boolean and methods.

This article has been dead for over six months. Start a new discussion instead.