Computer Science Canada

SleepThread

Author:  vicgnesh [ Sat Oct 20, 2007 10:48 pm ]
Post subject:  SleepThread

// The "Spiral" class.
import java.awt.*;
import hsa.Console;

public class Spiral
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();
int a = 100;
int b = 100;
int radx = 1;
int rady = 1;
// declare the variables for the spiral loop

for (int loop = 1 ; loop <=57 ; loop++)
{
c.drawOval (a, b, radx, rady);
a = a + 2;
b = b + 2;
radx = radx + 5;
rady = rady + 5;
}
// Place your program here. 'c' is the output console
} // main method
} // Spiral class


Question
My question is I want to use a sleep thread in the spiral so that the circle grows evenly every millisecond.

Please reply me to help me solve this question!

--Thanks in Advance

Author:  Euphoracle [ Sun Oct 21, 2007 1:22 am ]
Post subject:  RE:SleepThread

Thread.Sleep( <seconds> * 1000 ); should do it.

Author:  richcash [ Sun Oct 21, 2007 1:16 pm ]
Post subject:  Re: SleepThread

On a related note, does anyone know a method that returns the amount of time your program has been running/executing (equivalent to Turing's Time.Elapse)?

That way, you could properly slow down execution speed equally on all computers.

Author:  richcash [ Sun Oct 21, 2007 2:42 pm ]
Post subject:  Re: SleepThread

Okay, I found the method.
System.currentTimeMillis() will give you the current time in milliseconds. Therefore,
Java:
// this will give you the starting time
long start = System.currentTimeMillis();
// this will give you how long your program has been running at a certain point
long timeGone = System.currentTimeMillis() - start);

Similarly, System.nanoTime() will give you the current time in nanoseconds. 1 000 000 nanoseconds = 1 millisecond.

You can use System.currentTimeMillis() in conjunction with Thread.sleep() to limit execution speed equally on all computers.



Back to the original post, you must use Thread.sleep in a try-catch statement, or it will not work.
Java:
try {
        Thread.sleep(3000);
}
catch (InterruptedException e) {
}

That will delay your program by 3 seconds (or 3000 milliseconds).


: