java 创建一个线程循环获取数据,超过10秒后停止线程
时间: 2024-02-05 19:26:29 浏览: 25
您可以使用`Thread`类和`while`循环来实现这个功能。下面是一个示例代码:
```java
public class MyThread extends Thread {
private volatile boolean running = true;
public void run() {
long startTime = System.currentTimeMillis();
while (running) {
// 获取数据的逻辑
// ...
// 判断是否超过10秒
long currentTime = System.currentTimeMillis();
if (currentTime - startTime >= 10000) {
stopThread();
}
}
}
public void stopThread() {
running = false;
}
}
```
在`run`方法中,我们使用一个`while`循环来获取数据。在每次循环中,我们检查是否超过了10秒的时间限制。如果超过了,调用`stopThread`方法来停止线程。
使用示例代码创建并启动线程:
```java
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
// 休眠一段时间,模拟获取数据的过程
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 停止线程
thread.stopThread();
}
}
```
在这个示例中,我们创建了一个`MyThread`的实例并启动线程。然后,通过休眠15秒来模拟获取数据的过程。最后,调用`stopThread`方法来停止线程。注意,`stopThread`方法是自定义的,通过设置`running`变量为`false`来停止线程的执行。