能停止的线程_异常法
在线程中用for循环语句来判断一下线程是否是停止状态,如果是停止状态,则后面的代码不再运行即可。
实现代码如下:
自定义线程类
package com.thread5;
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("已经是停止状态了!我要退出了!");
throw new InterruptedException();
}
System.out.println("i=" + (i + 1));
}
//判断该代码是否执行//
System.out.println("我在for下面");
} catch (InterruptedException e) {
System.out.println("进MyThread.java类run方法中的catch了");
e.printStackTrace();
}
}
}
启动类
package com.thread5;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Run {
public static void main(String[] args) {
//控制台输出值文件
File f = new File("out.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintStream printStream = new PrintStream(fileOutputStream);
System.setOut(printStream);
//线程开启
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(2000);
myThread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!!");
}
}
执行结果
i=159845
i=159846
i=159847
i=159848
i=159849
i=159850
i=159851
i=159852
i=159853
i=159854
i=159855
i=159856
i=159857
i=159858
i=159859
i=159860
end!!
已经是停止状态了!我要退出了!
进MyThread.java类run方法中的catch了