其实现在要对一个循环执行的线程关闭,对循环执行体设置执行标志是常见的方法。另外一种方法是使用interrupt方法中断线程方式关闭线程。
使用interrupt方法中断线程来退出线程
sleep wait io阻塞的情况下,对于这种线程退出的可以采用这种方法。主要方法原理就是使用interrupt方法设置中断状态,然后在catch代码块中执行如下逻辑。
catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e(LOG_TAG, "I'M exit exit ....");
e.printStackTrace();
break;
}
来退出线程。
给子线程设置标志位关闭子线程
package chapter2;
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("线程退出!");
}
}
第二个例子
public class AlternateStop extends Object implements Runnable {
private volatile boolean stopRequested;//停止线程标志位
private Thread runThread;//指向当前执行的线程
public void run() {
runThread = Thread.currentThread();
stopRequested = false;
int count = 0;
while ( !stopRequested ) {
System.out.println("Running ... count=" + count);
count++;
try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
Thread.currentThread().interrupt();
//当设置线程中断时,sleep方法会抛InterruptedException 异常,也可以在这里退出执行。
}
}
System.out.println("stoped");
}
public void stopRequest() {//设置线程停止请求。
//同时设置标志位和设置线程中断标志
stopRequested = true;
if ( runThread != null ) {
runThread.interrupt();
}
}
public static void main(String[] args) {
AlternateStop as = new AlternateStop();
Thread t = new Thread(as);
t.start();
try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
as.stopRequest();
}
}
可能的运行结果如下:
Running ... count=0
Running ... count=1
Running ... count=2
Running ... count=3
Running ... count=4
Running ... count=5
Running ... count=6
stoped