您的位置:首页 > 编程语言 > Java开发

[转]Java 关闭线程的安全方法

2011-07-28 11:10 309 查看
http://www.blogjava.net/Green-nut/articles/335149.html

Java 之前有个api函数可以直接关闭线程, stop(), 后来, 取消了. 其替代的方式主要有两种:

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) {
///
//

数据处理
///
}
//super.run();
}

public static void main(String[] args) {
StopThread thread = new StopThread();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//停止线程
thread.stopThread(true);
}

}

2. 方法1 虽然可以可以处理好, 不过, 在有阻塞线程的语句的时候往往不能处理好. 比如, 设计到Socket的阻塞语句. 虽然java有提供异步io但是异步io是在程序里不断去查询有没有消息的, 所以耗电量可想而知, 对手机这种设备来说往往不适用.
那么阻塞的语句,怎么终止线程呢?
Java虽然deprecate了一个stop,但是,提供了interrupt(),这个方法是安全的. 这个中断方法可以将阻塞的线程唤醒过来, 但是注意 他不能将非阻塞的线程中断. 中断的同时,会抛出一个异常InterruptedException. 幸运的是, SocketChannel.connect() .read() 阻塞方法都会接受中断,ClosedByInterruptException.
这时我们不轮询变量了, 轮询当前线程是否被中断, 代码

package com.test;

public class StopThread extends Thread {

@Override
public void run() {
try {
System.out.println("start");
while(!this.isInterrupted()) {
///
//

数据处理
///

}
} 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");
}

}

3. Android 在自己的Api中加入了,Process类, 这个类可以直接终结进程, 也就是当前线程所在的JVM.
final static void killProcess(int pid) 其中,pid, 可以通过Process.mypid() 获取, 但这样终结的是整个程序, 不是我们所想要的.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: