package ExceptionBreak2;
public class TestMain {
public static void main(String[] args) throws InterruptedException {
MyThread mt = new MyThread();
mt.start();
Thread.sleep(200);
mt.interrupt();
}
}
package ExceptionBreak2;
public class MyThread extends Thread {
private int count;
public void run() {
try {
for (int i = 0; i < 100000; i++) {
System.out.println(this.isInterrupted());
System.out.println(i);
if (this.isInterrupted()) { // 若 为 中断状态则break
System.out.println(i);
System.out.println("end");
throw new Exception();
}
}
System.out.println("over");
} catch (Exception e) {
System.out.println("log");
}
}
}
2:RETURN 但是一般来说是建议使用异常的方法进行线程的停止 这样 线程会得以向上传播
package ReturnMethodStopThread;
public class TestMain {
public static void main(String[] args) throws InterruptedException {
MyThread mt = new MyThread();
mt.start();
Thread.sleep(2000);
mt.interrupt();
}
}
package ReturnMethodStopThread;
public class MyThread extends Thread {
public void run() {
while (1 == 1) {
if (this.interrupted()) {
System.out.println("OVER");
return;
}
System.out.println("Test");
}
}
}
停止线程的两种方式(异常和Return)
最新推荐文章于 2024-10-28 15:55:32 发布