首页 > 学院 > 开发设计 > 正文

结束线程的方法

2019-11-08 01:17:42
字体:
来源:转载
供稿:网友

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())。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表