For example, you can use the method with System.currentTimeMills() :
long start = System.currentTimeMillis(); long end = start + 60*1000; // 60 секунд* 1000 мс/сек while (System.currentTimeMillis() < end) { // work hard, play hard }
A source.
You can exit the program from another Thread :
public class ExitAfterMinute { public static void main(String args[]) { new Thread(new Runnable() { public void run() { try { Thread.sleep(60000); // минута в милисекундах } catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); } }).start(); while (true) { System.out.println("I'm doing something"); } } }
Or using a timer:
import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class TimedExit { Timer timer = new Timer(); TimerTask exitApp = new TimerTask() { public void run() { System.exit(0); } }; public TimedExit() { timer.schedule(exitApp, new Date(System.currentTimeMillis() + 60 * 1000)); } }
A source.
future.get(3, TimeUnit.SECONDS)- DimXenon