---
title: "线程的关闭"
author: "gu6866"
date: "2012-09-05T22:57:48Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-09-05T22:58:28Z"
id: 1672322
url: "https://premier9527.iteye.com/blog/1672322"
---

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

}