Botre Posted March 26, 2015 Share 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 Quote Link to comment Share on other sites More sharing options...
mustafa66 Posted March 26, 2015 Share Posted March 26, 2015 nice Quote Link to comment Share on other sites More sharing options...
Joseph Posted March 26, 2015 Share Posted March 26, 2015 (edited) like++ Edited March 26, 2015 by josedpay Quote Link to comment Share on other sites More sharing options...