标签:线程停止
之前介绍过,停机线程可以使用interrupte ,可以用标记,让run执行结束。现在我们来看几个方法。
方法1、使用interrupte方法来执行,通过抛出InterruptedException来结束run运行。
package secondThreadStudy;
import java.lang.InterruptedException;
public class MyThread extends Thread {
@Override
public void run(){
super.run();
try{
for ( int i = 0; i< 500000 ; i++ )
{
//判断该对象线程是否中断
if(this.interrupted()){
System.out.println("has interrupted! i am quit!");
throw new InterruptedException();
}
System.out.println("i am not executed , yeah !");
}
System.out.println("i am not executed ,too , yeah !");
}
catch(InterruptedException e)
{
System.out.println("exception has been catched");
e.printStackTrace();
}
}
}测试
package thirdThread;
public class Test {
public static void main(String[] args)
{
try{
MyThread boy = new MyThread();
boy.start();
Thread.sleep(2000);
boy.interrupt();
}catch(InterruptedException e)
{
System.out.println("main catch");
e.printStackTrace();
}
}
} 方法2、使用sleep和interrupt()停止线程。
package thirdThread;
import java.lang.InterruptedException;
public class MyThread extends Thread {
@Override
public void run(){
super.run();
try{
System.out.println("mythread sleep");
Thread.sleep(10000);
System.out.println("has interrupted! i am quit!");
}
catch(InterruptedException e)
{
System.out.println("exception has been catched");
e.printStackTrace();
}
}
} 方法3、使用stop,不推荐,也没什么好说的,就是说停就停,不管线程执行到哪了,只要stop就会停止,释放锁,对于同步多线程而言是很危险的。不举例子。
方法4、使用return,其实就是在run方法中,使用isInterrupted()判断,再直接return,让run方法结束。没什么好解释的。
方法5、其实使用interrupte方法,我的理解本质上是使用了boolean,假设不使用interrupte方法中断,而是在线程类中设置一个标志字段如flag,功能相当于interrupte,只是更加可控,在run方法,设置循环,条件即使检查flag是否为true,true则直接return,否则执行run方法中的剩余代码。通过设置线程的flag来使得线程自己知道合适推出,且每次退出都会在完成相关工作后。不高兴写代码了。
本文出自 “开心一杯茶” 博客,请务必保留此出处http://gugw9handsome.blog.51cto.com/1187812/1784200
标签:线程停止
原文地址:http://gugw9handsome.blog.51cto.com/1187812/1784200