Java程序如何设置固定运行时间,避免无限循环?

在Java程序中,如果需要设置一个固定运行时间,避免程序陷入无限循环,可以通过以下几种方法实现:
1. 使用
System.currentTimeMillis()
和
Thread.sleep()
通过记录开始时间,并使用
Thread.sleep()
方法暂停线程,可以在程序中实现固定运行时间的控制。
代码示例:
public class FixedRunTimeExample {
public static void main(String[] args) {
long startTime = System.currentTimeMillis(); // 记录开始时间

// 假设我们想要程序运行5秒钟
long runTime = 5000;

while (System.currentTimeMillis() – startTime < runTime) { // 这里可以放置需要执行的代码 System.out.println("程序正在运行..."); try { Thread.sleep(1000); // 每秒暂停一次 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("程序运行结束"); } } 2. 使用 ScheduledExecutorService ScheduledExecutorService 是Java并发包中的一个类,可以用来安排在给定的时间后运行的任务,或者定期执行任务。 代码示例: import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledExecutorServiceExample { public static void main(String[] args) { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // 安排任务在5秒后开始执行,并且每隔1秒执行一次 scheduler.scheduleAtFixedRate(() -> {
System.out.println(“任务正在执行…”);
}, 5, 1, TimeUnit.SECONDS);

// 等待任务执行完毕
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}

scheduler.shutdown();
}
}
3. 使用
CountDownLatch
CountDownLatch
是一个同步辅助类,在完成一组正在执行的操作之后,允许一个或多个线程继续执行。
代码示例:
import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
private static final CountDownLatch latch = new CountDownLatch(1);

public static void main(String[] args) throws InterruptedException {
// 假设我们想要程序运行5秒钟
long runTime = 5000;

new Thread(() -> {
try {
System.out.println(“程序开始运行…”);
Thread.sleep(runTime);
System.out.println(“程序运行结束”);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}).start();

latch.await(); // 等待程序运行结束
}
}
总结
以上是Java程序设置固定运行时间的几种方法。根据具体需求选择合适的方法,可以使程序在固定时间内运行,避免无限循环的问题。