I want to generate a random number every 2 seconds in my java (Android) program continuously for at least 10 minutes. But I just want to pause / delay the execution of the code with only one method, and not the whole program.
I tried using Thread like this -
boolean stop = false;
int random_number = 0;
while(true){
if(stop){
return;
}
random_number = Math.random();
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
However, this does not work how to Thread.sleepstop the execution of the entire program instead of just stopping the execution of the code inside the method, and my whole screen becomes blank.
I also tried using Handler, but it didn’t work, as it does not stop the execution of the code in my method and instead just stacks.
This will demonstrate his work better -
while(true){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
System.out.println("After 2 secs");
}
}, 2000);
System.out.println("Before 2 secs");
}
, , while .
, Android, Java SE 6, scheduleAtFixedRate. , ?
!