结束线程有两种方式:
(1)自然消亡
线程从run()方法的结尾处返回,自然消亡不会再调用
pubie class HelloWorld extends Thread (
private boolean flag=true;
//跳出循环标记量
public boolean isFlag(){
//标记量取值
return this.flag;
}
public void setFlag(boolean flag){
//标记量赋值
this. flag=flag;
}
public void run(){
while(isFlag()){
//执行相关业务操作
if(!isFlag()){
return;
//如果标记量为false,结束循环
}
}
}
}
(2)强制消亡
Java中原来在Thread中提供了stop()方法来终止线程,但这个方法是不安全的,所以一般不建议使用。
目前使用interrupt方法中断线程
分为两种情况:
(1)线程处于阻塞状态,如使用了sleep方法。
(2)使用while(!isInterrupted()){……}来判断线程是否被中断。
public class ThreadInterrupt extends Thread
{
public void run()
{
try
{
sleep(50000); // 延迟50秒
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception
{
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println("在50秒之内按任意键中断线程!");
System.in.read();
//中断
thread.interrupt();
//当前执行的线程停下来等待
thread.join();
System.out.println("线程已经退出!");
}
}
运行结果

一些课堂笔记






5984

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



