import java.util.*;
public class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
Thread.sleep(10000);//主线程睡眠
} catch(InterruptedException e) { }
thread.interrupt(); //-----------不是最好的方法
//thread.flag = false; //-----------此方法是终止线程的推荐方法
}
}
class MyThread extends Thread {
boolean flag = true;
public void run() {
//每隔一秒钟打印一次时间
while(flag) {
System.out.println
("====" + new Date() + "====");
try{
sleep(1000);
} catch(InterruptedException e) { //----此异常必须处理
return;
}
}
}
}
java例程练习(多线程[sleep()方法])
最新推荐文章于 2024-03-27 19:21:20 发布
本文展示了一个使用Java实现线程中断与终止的例子。通过一个简单的程序演示了如何创建线程,并在主线程中通过调用interrupt()方法来中断线程。此外还介绍了通过设置标志位来优雅地终止线程的方法。
413

被折叠的 条评论
为什么被折叠?



