在Java中有三种方法可以终止正在运行的线程
1,使用退出标志使线程退出,也就是run方法完成后线程终止
2,使用stop方法强行终止线程,但不推荐,因为stop和suspend及resume一样,都是作废过期的方法,使用它们会产生不可预料的效果
3,使用interrupt中断线程(只是打了一个停止标记,不是真正停止)
interrupt方法停止线程操作
package com.test.Thread.t7;
/**
* interrupt方法停止线程
* 使用interrupt中断线程(只是打了一个停止标记,不是真正停止)
* @author admin
* 2017年4月13日
*/
public class MyThread2 extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
for (int i = 0; i <5000000; i++) {
System.out.println("i==="+(i+1));
}
}
public static void main(String[] args) throws InterruptedException {
MyThread2 m2=new MyThread2();
m2.start();
Thread.sleep(2000);
m2.interrupt(); //线程并没有停止
}
}
如何判断线程状态是否停止的?
Java sdk中Thread.java类有两个方法可以判断
this.isInterrupted(); 测试线程是否中断
this.interrupted(); 测试当前线程是否已经中断
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println("是否停止=1 "+Thread.interrupted());
System.out.println("是否停止=2 "+Thread.interrupted());
System.out.println("end!");
}
运行后输出
是否停止=1 true
是否停止=2 false
end!
从上述结果看 方法interrupted的确判断出当前线程是否是停止状态 为什么第二个布尔值是fasle?官方帮助文档是这样解释的 如果连续两次调用该方法 第二次会返回false(第一次调用完成后会清除中断状态)
isInterrupted方法正好相反 不会清除中断状态
线程的暂停与恢复
suspend()方法暂停线程
resume()方法恢复线程的执行
缺点:容易造成公共的同步的对象的独占,使得其它线程无法访问公共的同步对象
package com.test.Thread.t8;
/**
* 使用suspend与resume方法的使用
* suspend()方法暂停线程
* resume()方法恢复线程的执行
* @author admin
* 2017年4月13日
*/
public class MyThread extends Thread{
private long i=0;
public long getI() {
return i;
}
public void setI(long i) {
this.i = i;
}
@Override
public void run() {
while(true){
i++;
}
}
}
package com.test.Thread.t8;
/**
* 使用suspend与resume方法的使用
* suspend()方法暂停线程
* resume()方法恢复线程的执行
* @author admin
* 2017年4月13日
*/
public class Run {
public static void main(String[] args) throws InterruptedException {
MyThread thread=new MyThread();
thread.start();
Thread.sleep(5000);
//A
thread.suspend(); //暂停
System.out.println("A="+System.currentTimeMillis()+" i=="+thread.getI());
Thread.sleep(5000);
System.out.println("A="+System.currentTimeMillis()+" i=="+thread.getI());
//B
thread.resume(); //恢复执行
Thread.sleep(5000);
//C
thread.suspend(); //暂停
System.out.println("B="+System.currentTimeMillis()+" i=="+thread.getI());
Thread.sleep(5000);
System.out.println("B="+System.currentTimeMillis()+" i=="+thread.getI());
}
}