您的位置:首页技术文章
文章详情页

如何设置一个无限循环并打破它。(Java线程)

【字号: 日期:2024-05-01 11:04:30浏览:64作者:猪猪
如何解决如何设置一个无限循环并打破它。(Java线程)?

假设您在JDK 1.5或更高版本(澄清和改进了内存模型)上运行,则可以使用

public class MyRunnable extends Runnable{ private volatile boolean cancelled; public void run() { while (!cancelled) { doStuff(); } } public void cancel() { cancelled = true; } public boolean isCancelled() { return cancelled; }}j

或者,使用java.util.concurrent.Future和FutureTask,它们支持立即取消。

解决方法

我已经设置了一个线程,我想使用循环来运行它。因此,该线程应在循环中运行并在一定时间内中断,然后再次运行循环。

请我不知道该怎么做。有人可以指导我。

标签: java
相关文章: