如何停止一个正在运行的线程
1)设置标志位
如果线程的run方法中执行的是一个重复执行的循环,可以提供一个标记来控制循环是否继续
代码示例:
public class fundemo02 {
/**
* 练习2:设计一个线程:运行10秒后被终止(掌握线程的终止方法)
* @param args
*/
public static void main(string[] args) throws exception{
myrunable02 runnable = new myrunable02();
new thread(runnable).start();
thread.sleep(10000); // 主线程休眠10秒钟
runnable.flag = false;
system.out.println("main、 end ...");
}
}
class myrunable02 implements runnable{
boolean flag = true;
@override
public void run() {
while(flag){
try {
thread.sleep(1000);
system.out.println(new date());
} catch (interruptedexception e) {
e.printstacktrace();
}
}
system.out.println(thread.currentthread().getname() + " 执行完成");
}
}2)利用中断标志位
在线程中有个中断的标志位,默认是false,当我们显示的调用 interrupted方法或者isinterrupted方法是会修改标志位为true。
我们可以利用此来中断运行的线程。
代码示例:
package com.bobo.fundemo;
public class fundemo07 extends thread{
public static void main(string[] args) throws interruptedexception {
thread t1 = new fundemo07();
t1.start();
thread.sleep(3000);
t1.interrupt(); // 中断线程 将中断标志由false修改为了true
// t1.stop(); // 直接就把线程给kill掉了
system.out.println("main .... ");
}
@override
public void run() {
system.out.println(this.getname() + " start...");
int i = 0 ;
// thread.interrupted() 如果没有被中断 那么是false 如果显示的执行了interrupt 方法就会修改为 true
while(!thread.interrupted()){
system.out.println(this.getname() + " " + i);
i++;
}
system.out.println(this.getname()+ " end .... ");
}
}3)利用interruptedexception异常
如果线程因为执行join(),sleep()或者wait()而进入阻塞状态,此时要想停止它,可以让他调用interrupt(),程序会抛出interruptedexception异常。
我们利用这个异常可以来终止线程。
package com.bobo;
public class fundemo08 extends thread{
public static void main(string[] args) throws interruptedexception {
thread t1 = new fundemo08();
t1.start();
thread.sleep(3000);
t1.interrupt(); // 中断线程 将中断标志由false修改为了true
// t1.stop(); // 直接就把线程给kill掉了
system.out.println("main .... ");
}
@override
public void run() {
system.out.println(this.getname() + " start...");
int i = 0 ;
// thread.interrupted() 如果没有被中断 那么是false 如果显示的执行了interrupt 方法就会修改为 true
while(!thread.interrupted()){
//while(!thread.currentthread().isinterrupted()){
try {
thread.sleep(10000);
} catch (interruptedexception e) {
e.printstacktrace();
break;
}
system.out.println(this.getname() + " " + i);
i++;
}
system.out.println(this.getname()+ " end .... ");
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论