Botre Posted March 26, 2015 Posted March 26, 2015 (edited) A quick example of a ConditionalLoop class. The API one is great and I suggest you use that one, this is more for learning purposes. package org.bjornkrols.conditional; import org.bjornkrols.imported.MilliTimer; /** * @author Bjorn Krols (Botre) * @version 0.1 * @since March 26, 2015 */ public abstract class ConditionalLoop extends Thread { /** * This loop's timer (millisecond precision). */ private MilliTimer timer; /** * The maximum (exclusive) time of looping, in milliseconds, after which the loop will be broken. */ private int timeout; public ConditionalLoop(final int timeout) { setDaemon(true); setTimeout(timeout); } /** * A no-argument constructor with a default timeout of 10 seconds. */ public ConditionalLoop() { this(10000); } @Override public void run() { preLoop(); while (condition()) { if (timer.getElapsedMilliSeconds() > timeout) { onTimeout(); break; } try { Thread.sleep(onLoop()); } catch (InterruptedException e) { e.printStackTrace(); } } postLoop(); } /** * @return Whether to continue to loop. */ public abstract boolean condition(); /** * Executes before the loop starts. */ public void preLoop() { timer = new MilliTimer(); }; /** * The actual loop. * * @return The time to sleep for, in milliseconds, after each iteration. */ public abstract int onLoop(); /** * Executes after the loop. */ public void postLoop() { }; /** * Executes when the loop has timed out. */ public void onTimeout() { } /** * Sets the timeout (in milliseconds). * * @param milliseconds The time out (in milliseconds). */ public void setTimeout(int milliseconds) { timeout = milliseconds; } } Edited March 26, 2015 by Botre 1