Si no puede exceder su límite de tiempo (es un límite difícil), entonces un hilo es su mejor opción. Puede usar un ciclo para terminar el hilo una vez que llegue al umbral de tiempo. Lo que esté sucediendo en ese hilo en ese momento puede interrumpirse, permitiendo que los cálculos se detengan casi al instante. Aquí hay un ejemplo:
Thread t = new Thread(myRunnable); // myRunnable does your calculations
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;
t.start(); // Kick off calculations
while (System.currentTimeMillis() < endTime) {
// Still within time theshold, wait a little longer
try {
Thread.sleep(500L); // Sleep 1/2 second
} catch (InterruptedException e) {
// Someone woke us up during sleep, that's OK
}
}
t.interrupt(); // Tell the thread to stop
t.join(); // Wait for the thread to cleanup and finish
Eso le dará una resolución de aproximadamente 1/2 segundo. Al sondear con más frecuencia en el ciclo while, puede obtenerlo. plazo
Su del ejecutable sería algo como esto:
public void run() {
while (true) {
try {
// Long running work
calculateMassOfUniverse();
} catch (InterruptedException e) {
// We were signaled, clean things up
cleanupStuff();
break; // Leave the loop, thread will exit
}
}
Actualización basada en la respuesta de Dimitri
Dmitri señaló TimerTask, lo que permitiría a evitar el bucle. Podrías simplemente hacer la llamada de unión y el TimerTask que configuraste se encargaría de interrumpir el hilo. Esto le permitiría obtener una resolución más exacta sin tener que sondear en un bucle.
Parece que estamos refrito de un viejo hilo aquí: http://stackoverflow.com/questions/2550536/java-loop-for-a-certain-duration – Dmitri
Compruebe este artículo: http: // www. yegor256.com/2014/06/20/limit-method-execution-time.html – yegor256
Posible duplicado de [Cómo agotar el tiempo de espera de un hilo] (http://stackoverflow.com/questions/2275443/how-to-timeout-a -thread) – vhunsicker