结束线程的方法

Thread 和 Runnable
(1)Theread是个类。 run()、getName()方法
(2)Runnable是一个接口。Thread.currentThread().getName()
Runnable 创建对象方法:Thread acctressThread = new Thread(new Actress(),”Ms.Runnable”);

结束线程的三种方法:
1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。

2.  使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。 

3.  使用interrupt方法中断线程。

1、使用退出标志
public class exampleThread extends Thread{

public void run(){
    boolean keepRunning = true;//设置标志为true
    int count = 0;
    while(keepRunning){
        System.out.println("线程进行中:"+(++count));

        if(count == 100){
            keepRunning = false;//结束线程标志
            System.out.println("线程结束了");
        }
    }
}
public static void main(String[] args) {
    Thread th = new exampleThread();
    th.start();

}

}

2. 使用stop方法终止线程 

使用stop方法可以强行终止正在运行或挂起的线程。我们可以使用如下的代码来终止线程: 

thread.stop();

虽然使用上面的代码可以终止线程,但使用stop方法是很危险的,就象突然关闭计算机电源,而不是按正常程序关机一样,可能会产生

不可预料的结果,因此,并不推荐使用stop方法来终止线程。

3. 使用interrupt方法终止线程 

使用interrupt方法来终端线程可分为两种情况: 

(1)线程处于阻塞状态,如使用了sleep方法。 

(2)使用while(!isInterrupted()){……}来判断线程是否被中断。 

在第一种情况下使用interrupt方法,sleep方法将抛出一个InterruptedException例外,而在第二种情况下线程将直接退出。下面的代

码演示了在第一种情况下使用interrupt方法。

package chapter2;

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(“线程已经退出!”);
}
}

上面代码的运行结果如下: 

在50秒之内按任意键中断线程! 

sleep interrupted 
线程已经退出! 


在调用interrupt方法后, sleep方法抛出异常,然后输出错误信息:sleep interrupted. 

注意:在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个是静态的方法interrupted(),一个是非静态的方

法isInterrupted(),这两个方法的区别是interrupted用来判断当前线是否被中断,而isInterrupted可以用来判断其他线程是否被中断

。因此,while (!isInterrupted())也可以换成while (!Thread.interrupted())。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值