android多线程之二:终止线程的三种方法
2017-09-02 22:43
489 查看
有三种方法可以终止线程:
有时候为了完成一些需要重复执行的任务,如服务器监听客户端的请求,会在线程的run方法中使用while(true){……}来处理,但要想使while循环在某一特定条件下退出,最直接的方法就是设一个boolean类型的标志,并通过设置这个标志为true或false来控制while循环是否退出,例子:
在上面代码中定义了一个退出标志exit,当exit为true时,while循环执行,exit的默认值为false.在定义exit时,使用了一个Java关键字volatile,这个关键字的目的是使exit同步,也就是说在同一时刻只能由一个线程来修改exit的值,
虽然使用上面的代码可以终止线程,但使用stop方法是很危险的,就象突然关闭计算机电源,而不是按正常程序关机一样,可能会产生不可预料的结果,因此,并不推荐使用stop方法来终止线程。
1.线程处于堵塞状态,如使用了sleep方法,这时候如果使用interrupt方法,会抛出InterruptedException异常,所以捕捉这个异常来退出线程:
2.线程处于非堵塞状态,在线程的run方法中判断
注意:在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个是静态的方法
这两个方法的区别是interrupted用来判断当前线是否被中断,而isInterrupted可以用来判断其他线程是否被中断。
因此,
一.使用退出标志位
使用退出标志位,使线程正常退出,也就是当run方法完成后线程终止。有时候为了完成一些需要重复执行的任务,如服务器监听客户端的请求,会在线程的run方法中使用while(true){……}来处理,但要想使while循环在某一特定条件下退出,最直接的方法就是设一个boolean类型的标志,并通过设置这个标志为true或false来控制while循环是否退出,例子:
public class ThreadFlag extends Thread { public volatile boolean exit = false; public void run() { while (!exit); } public static void main(String[] args) throws Exception { ThreadFlag thread = new ThreadFlag(); thread.start(); sleep(5000); // 主线程延迟5秒 thread.exit = true; // 终止线程thread thread.join(); System.out.println("线程退出!"); } }
在上面代码中定义了一个退出标志exit,当exit为true时,while循环执行,exit的默认值为false.在定义exit时,使用了一个Java关键字volatile,这个关键字的目的是使exit同步,也就是说在同一时刻只能由一个线程来修改exit的值,
二.使用stop方法终止线程
使用stop方法可以强行终止正在运行或挂起的线程。我们可以使用如下的代码来终止线程:thread.stop();
虽然使用上面的代码可以终止线程,但使用stop方法是很危险的,就象突然关闭计算机电源,而不是按正常程序关机一样,可能会产生不可预料的结果,因此,并不推荐使用stop方法来终止线程。
三.使用interrupt方法终止线程
使用interrupt方法来终端线程可分为两种情况:1.线程处于堵塞状态,如使用了sleep方法,这时候如果使用interrupt方法,会抛出InterruptedException异常,所以捕捉这个异常来退出线程:
public class ThreadInterrupt extends Thread { public void run() { try { sleep(50000); // 延迟50秒 } catch (InterruptedException e) //2.捕捉InterruptedException { System.out.println(e.getMessage()); return; //3.退出线程 } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); thread.interrupt(); //1.使用interrupt方法 thread.join(); System.out.println("线程已经退出!"); } }
2.线程处于非堵塞状态,在线程的run方法中判断
while(!isInterrupted()){……}:
public class ThreadInterrupt extends Thread { public void run() { while(!isInterrupted()) { …… } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); thread.interrupt(); thread.join(); System.out.println("线程已经退出!"); } }
注意:在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个是静态的方法
interrupted(),一个是非静态的方法
isInterrupted(),
这两个方法的区别是interrupted用来判断当前线是否被中断,而isInterrupted可以用来判断其他线程是否被中断。
因此,
while (!isInterrupted())也可以换成
while (!Thread.interrupted())。
相关文章推荐
- android 停止 终止 Thread 线程的三种方法
- Android 三种线程使用方法
- Android开发中终止线程方法
- Android终止线程的方法
- Android 终止线程的方法
- 终止线程的三种方法
- android 终止线程几种方法
- Android 中三种启用线程的方法
- 【java】终止线程的三种方法
- Android 中三种使用线程的方法
- android跨线程更新UI的三种方法
- 终止线程的三种方法
- 终止线程的三种方法
- 终止线程的三种方法
- 终止java线程的三种方法
- 使用线程创建的三种方法实现j2me联网(PS:我想做android!NND!)
- 终止线程的三种方法
- Java中终止线程的三种方法
- Android子线程中更新UI的三种方法和获取message的两种方法总结
- Android安卓开发中终止线程方法