使用布尔值停止 Java 线程
可以通过实现 Runnable 接口并重写 run() 方法来创建线程。然后可以创建一个 Thread 对象并调用 start() 方法。
可以使用 Java 中的布尔值停止线程。当布尔值 stop 为 false 时,线程运行,当布尔值 stop 变为 true 时,它停止运行。
演示此内容的程序如下所示
示例
class ThreadDemo extends Thread {
public boolean stop = false;
int i = 1;
public void run() {
while (!stop) {
try {
sleep(10000);
} catch (InterruptedException e) {
}
System.out.println(i);
i++;
}
}
}
public class Demo {
public static void main(String[] args) {
ThreadDemo t = new ThreadDemo();
t.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
t.stop = true;
System.out.println("The thread is stopped");
}
}输出
1 2 3 4 5 The thread is stopped
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP