0

I am making a slapjack game where the deck will need to give to cards to the slapzone every 5 seconds and flip the image for 2 seconds before turning the picture back over. I know i will have to use a thread, but i can't figure out how to say repeat every 5 seconds i know the repeating part will take a for loop though.

Code:

public void run ()
{
    Thread thisThread = Thread.currentThread();     
    while (thisThread == myThread)         
    {
        try
        {
            for (int i = 0 ; i < numcards ; i++)
            {
                deck.giveslapZone(slap1); 
            }

            myThread = null;                // kills the thread 
        }
        catch (InterruptedException ie) 
        {
            System.out.println(ie.getMessage());    
        }
    }
}
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41

2 Answers2

0

you can make your class implements Runnable and then declare Thread thread = new Thread(this); and then: for eg.

public void run() {
    while(true) {
        try
        {
            for (int i = 0; i < numcards; i++)
            {
                deck.giveslapZone(slap1); 
            }
            thread.sleep(5000);
        }
        catch (InterruptedException ie) 
        {
            System.out.println(ie.getMessage());    
        }
    }
}
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
Michał
  • 1
  • 2
0

You can use ScheduledThreadPoolExecutor if you believe this may grow past a trivial implementation. A Scheduler thread would handle multiple threads and exceptions in a much smoother manner.

See the example in...

TimerTask vs Thread.sleep vs Handler postDelayed - most accurate to call function every N milliseconds?

Community
  • 1
  • 1
kervin
  • 11,672
  • 5
  • 42
  • 59