线程停止方法:
1.stop(不推荐使用)
2.使用interrupt()退出线程,再根据interrupted()或者isInterrupted()来判断是否线程状态为停止,return与抛异常来推出线程;
3.在睡眠中退出线程;Thread.sleep(),在interrupt()退出线程,会报错,退出线程。
使用interrupt()退出线程:
public class MainThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
if(this.isInterrupted()){
System.out.println("退出线程");
return;
}
System.out.println(i);
}
}
}
public class Text {
public static void main(String[] args) {
try {
MainThread ma = new MainThread();
ma.start();
Thread.sleep(100);
ma.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
休眠退出
public class MainThread extends Thread{
@Override
public void run() {
try {
Thread.sleep(20000);
} catch (Exception e) {
System.out.println("退出线程");
}
}
}
public class Text {
public static void main(String[] args) {
try {
MainThread ma = new MainThread();
ma.start();
Thread.sleep(100);
ma.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}