Delayed code execution in a Java method

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){  //if stop becomes true, then
        return;  //terminate the method
    }

    random_number = Math.random(); //generate random number
                                   //which is used bu some other
                                   //part of code
    try {
        Thread.sleep(2000);        //delay the code for 2 secs
    } catch(InterruptedException ex) {  //and handle the exceptions
        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"); //this gets printed
                                               //later
        }
    }, 2000);
    System.out.println("Before 2 secs"); //this gets printed first
}

, , while .

, Android, Java SE 6, scheduleAtFixedRate. , ?

!

+4
4

1: , (UI):

new Thread(new Runnable() {
  // some code here ...

  // This might be in a loop.
  try {
    Thread.sleep(2000);
  } catch(InterruptedException ex) {
    // Handle ...
  }
 }
}).start();

, UI (, / , - ..), , . Activity.runOnUiThread() .

2: , Android AsyncTask. , . . . :

 private class MyTask extends AsyncTask<Void, Void, Void> {
   protected Void doInBackground(Void... param) {
     // This method is running off the UI thread.
     // Safe to stop execution here.

     return null;
   }

   protected void onProgressUpdate(Void... progress) {
     // This methid is running on the UI thread. 
     // Do not stop thread here, but safe to modify the UI.
   }

   protected void onPostExecute(Long result) {
     // Also on UI thread, executed once doInBackground()
     // finishes.
   }
 }

3: Timer, @Stultuske. , AsyncTask, .

+5
private Timer timer;
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                //Generate number
            }
        }, 2000, 2000);

//Documentation (From SDK)
/**
             * Schedule a task for repeated fixed-rate execution after a specific delay
             * has passed.
             *
             * @param task
             *            the task to schedule.
             * @param delay
             *            amount of time in milliseconds before first execution.
             * @param period
             *            amount of time in milliseconds between subsequent    executions.
    public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
                if (delay < 0 || period <= 0) {
                    throw new IllegalArgumentException();
                }
                scheduleImpl(task, delay, period, true);
    }

timer.cancel()
+4

, Handler.

/ while (, , , , ).

, Runnable. Runnable . , runnable delayed, , .

final Handler handler = new Handler();
Runnable runnable = new Runnable() {

    @Override
    public void run() {
        System.out.println("After 2 secs");
        random_number = Math.random();

        if (!stop) // should not be stopped, so we add another runnable;
        {
          handler.postDelayed(this, 2000);
        }
   }

handler.postDelayed(runnable, 2000);

, Handler , - , , .

He could do 1 minute of correct operation, and then block it for 1.4 seconds, when the device goes into sleep mode, and after turning it on again, the processor will make the remaining 0.6 seconds.

However, without knowing your needs, you may not be affected by this behavior, and the answer may fit you.

+4
source

if you want to use thread do the following:

Thread t = new Thread(){
    public void run(){
      while(true){
         if(stop) break;
         random_number = Math.random();
         sleep(2000);
      }
    }
};
t.start();
+2
source

All Articles