使用线程来保持时间:
public class KeepingTime
{
private volatile int timeTaken;
private Thread timekeeper;
public KeepingTime()
{
timekeeper = new Thread(new Runnable(){
public void run()
{
try
{
while(true)
{
Thread.sleep(1000);
timeTaken++;
if(Thread.interrupted())
return;
}
}
catch(InterruptedException e)
{
return;
}
} //end run
}); //end thread
timekeeper.start();
} //end constructor
public void stop()
{
timekeeper.interrupt();
}
public int timeTaken()
{
return timeTaken;
}
}
然后像这样使用它:
for(String question : questions)
{
KeepingTime timer = new KeepingTime();
//ask the question
//wait until it is answered
timer.stop();
int timeTaken = timer.timeTaken();
}
请注意,我没有使用 Thread.stop() 因为它已被弃用。如果您运行大量线程,这可能会不一致。