怎么叫这个线程结束呢??
来源:百度知道 编辑:UC知道 时间:2024/06/21 09:04:38
import java.util.Date;
public class TestSleep {
public static void main(String[] args) {
xiancheng a = new xiancheng();
Thread b = new Thread(a);
b.start();
}
}
class xiancheng implements Runnable {
boolean flag = true;
public void run() {
while (true) {
System.out.println("-----" + new Date() + "-----");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
public class TestSleep {
public static void main(String[] args) {
xiancheng a = new xiancheng();
Thread b = new Thread(a);
b.start();
}
}
class xiancheng implements Runnable {
boolean flag = true;
public void run() {
while (true) {
System.out.println("-----" + new Date() + "-----");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
想让这个线程结束?
boolean flag = true;
public void run() {
while (true) {
你这里既然已经定义了一个标识干嘛不用?
public static flag=true
public void run() {
while (flag) {
然后你就可以在外面设置flag为false的时候,线程就结束了
你这个线程和程序的生命同期同样长,除非强制关闭。否则永远运行(资源耗尽也有可能);
一个线成结束 就是 你的 run方法运行完成
b.stop()可以停止此线程