1.不要手动调用stop方法强行终止一个线程,这种方式不安全。
复制代码
2. 方法1 虽然可以可以处理好, 不过, 在有阻塞线程的语句的时候往往不能处理好. 比如, 设计到Socket的阻塞语句. 虽然java有提供异步io但是异步io是在程序里不断去查询有没有消息的, 所以耗电量可想而知, 对手机这种设备来说往往不适用.
那么阻塞的语句,怎么终止线程呢?
Java虽然deprecate了一个stop,但是,提供了interrupt(),这个方法是安全的. 这个中断方法可以将阻塞的线程唤醒过来, 但是注意 他不能将非阻塞的线程中断. 中断的同时,会抛出一个异常InterruptedException. 幸运的是, SocketChannel.connect() .read() 阻塞方法都会接受中断,ClosedByInterruptException.
这时我们不轮询变量了, 轮询当前线程是否被中断, 代码
通过帮助文档,我们可以知道,Android的线程类本身就提供了一些公共方法去结束线程。
final void
This method is deprecated. because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state
但是,通过说明我们可以看到,这些方法Android本身都是不推荐使用的,通过这种方式结束线程是不安全的。
2.线程里run函数短,执行完后线程会自行销毁,不用手动去终止。
3.手动停止,通过在run里设置标志先停止运行,再调用Thread.interrupt();注意,在run没有停止时调用.interrupt()没有效果。
1. 自己加入一个成员变量, 我们在程序的循环里面, 轮流的去检查这个变量, 变量变化时,就会退出这个线程. 代码示例如下
- package com.test;
- public class StopThread extends Thread {
- private boolean _run = true;
- public void stopThread( boolean run) {
- this ._run = !run;
- }
-
- @Override
- public void run() {
- while(_run) {
-
- //[img]http://www.blogjava.net/Images/dot.gif[/img]数据处理
那么阻塞的语句,怎么终止线程呢?
Java虽然deprecate了一个stop,但是,提供了interrupt(),这个方法是安全的. 这个中断方法可以将阻塞的线程唤醒过来, 但是注意 他不能将非阻塞的线程中断. 中断的同时,会抛出一个异常InterruptedException. 幸运的是, SocketChannel.connect() .read() 阻塞方法都会接受中断,ClosedByInterruptException.
这时我们不轮询变量了, 轮询当前线程是否被中断, 代码
- System.out.println("start");
- while(!this.isInterrupted()) {
- [img]http://www.blogjava.net/Images/dot.gif[/img]数据处理
-
-
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println(stop);
- super.run();
- }
- public static void main(String[] args) {
- StopThread thread=new StopThread();
- thread.start();
- try {
- Thread.sleep(1000);
- }catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- thread.interrupt();
- System.out.println(interrupt);
- }
- }