很多情况会造成线程停止运行:
- 线程执行完毕自动停止
- 线程执行过程中遇到错误抛出异常并停止
- 线程执行过程中根据需求手动停止
Java中实现线程中断有如下几种常用方法:
-
public void stop() 在新版JDK中已不推荐使用
-
public void interrupt()
-
public boolean isInterrupted()
public void interrupt() { if (this != Thread.currentThread()) checkAccess(); synchronized (blockerLock) { Interruptible b = blocker; if (b != null) { interrupt0(); // Just to set the interrupt flag b.interrupt(this); return; } } interrupt0(); }
public State getState() { // get current thread state return sun.misc.VM.toThreadState(threadStatus); }
public boolean isInterrupted() { return isInterrupted(false); }
interrupt是一个实例方法,当一个线程对象调用该方法时,表示中断当前线程对象。
每个线程对象都是通过一个标志位来判断当前是否为中断状态。
isInterrupted就是用来获取当前线程对象的标志位:true表示清除了当前标志位,当前线程已中断;false表示没有清除标志位,当前对象没有中断。
当一个线程对象处于不同的状态时,中断机制也是不同的。
创建状态:实例化线程对象,不启动。
package com.mie.interrupt;
public class Test {
public static void main(String[] args) {
Thread thread=new Thread();
System.out.println(thread.getState());
thread.interrupt();//线程中断
System.out.println(thread.isInterrupted());//判断当前线程是否中断
}
}
测试结果:
NEW表示当前线程对象位创建状态,false表示当前线程并未中断,因为当前线程没有启动,何来中断。
匿名内部类
package com.mie.interrupt;
public class Test2 {
public static void main(String[] args) {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i+"main======");
}
}
});
thread.start();
}
}
package com.mie.interrupt;
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i+"main=====");
}
}
}
package com.mie.interrupt;
public class Test2 {
public static void main(String[] args) {
// Thread thread=new Thread(new Runnable() {
//
// @Override
// public void run() {
// for (int i = 0; i < 10; i++) {
// System.out.println(i+"main======");
// }
//
// }
// });
// thread.start();
MyRunnable myRunnable=new MyRunnable();
Thread thread=new Thread(myRunnable);
thread.start();
}
}
测试结果和匿名内部类一样:
package com.mie.interrupt;
public class Test2 {
public static void main(String[] args) {
// Thread thread=new Thread(new Runnable() {
//
// @Override
// public void run() {
// for (int i = 0; i < 10; i++) {
// System.out.println(i+"main======");
// }
//
// }
// });
// thread.start();
MyRunnable myRunnable=new MyRunnable();
Thread thread=new Thread(myRunnable);
thread.start();
System.out.println(thread.getState());//获取线程状态
thread.interrupt();//中断线程
System.out.println(thread.isInterrupted());//判断线程是否中断
System.out.println(thread.getState());//再次获取线程状态
}
}
getState方法是返回当前的线程状态
几种线程状态源码: