Java - code block execution time selection

hi I want a block of code (certain function lines) that will be executed for a certain period of time (for example, x milliseconds). Is it possible to do this in java?

+3
source share
5 answers

1st approach:

long startTime = System.nanoTime();
while(System.nanoTime() - startTime < MAX_TIME_IN_NANOSECONDS){
   // your code ...
}

Second approach

Start your code on the stream.

Skip the main thread until you need to.

Kill (stop, interrupt) your thread.

+2
source

either use the exit condition based on the current timestamp, or create a separate thread and kill it after the specified timeout.

+2
source

, . Future . , TimeoutException, . . , .

:

ExecutorService exec = Executors.newSingleThreadExecutor();
Future<Integer> future = exec.submit(new Callable<Integer>(){
    @Override
    public Integer call() throws Exception {

        //do some stuff

        //periodically check if this thread has been interrupted
        if (Thread.currentThread().isInterrupted()) {
            return -1;
        }                    

        //do some more stuff

        //check if interrupted
        if (Thread.currentThread().isInterrupted()) {
            return -1;
        }

        //... and so on

        return 0;
    }
});
exec.shutdown();

try {
    //wait 5 seconds for the task to complete.
    future.get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
} catch (TimeoutException e) {
    //the task did not complete in 5 seconds
    e.printStackTrace();
    System.out.println("CANCELLING");

    //cancel it
    future.cancel(true); //sends interrupt
}
+1

:

timeInMilis = Calendar.getInstance().getTimeInMillis();
while(Calendar.getInstance().getTimeInMilis() - timeInMilis < MAX_TIME_IN_MILIS){
    // Execute block
}
0

System.currentTimeMillis() , .

long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
  // do your stuff
}

- , .

  long timeLeft = endTime - System.currentTimeMillis();
  if (sleepAmount > timeLeft)
    sleepAmount = timeLeft;
  Thread.sleep(sleepAmount);

wait() notify(), timeLeft wait(), . , .

  long timeLeft = endTime - System.currentTimeMillis();
  if (timeLeft > 0)
    this.wait(timeLeft);

, , , , , , . . , , , , ? , .

long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
  this.doFirstLongThing();
  if (System.currentTimeMillis() >= endTime) break;
  this.doSecondLongThing();
  if (System.currentTimeMillis() >= endTime) break;
  this.doThirdLongThing();
}
0

Source: https://habr.com/ru/post/1784570/


All Articles