异常法和return法
来源:互联网 发布:淘宝口碑店铺 编辑:程序博客网 时间:2024/06/05 14:45
public static void main(String[] args) {
try {
ExceptionStopThread thread = new ExceptionStopThread();
thread.start();
thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main cactch");
e.printStackTrace();
}
System.out.println("end");
}
}
public class ExceptionStopThread extends Thread {
@Overridepublic void run() {
super.run();
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println("Thread stop.");
break;
}
System.out.println("i = " + i);
}
}
}
public class ThreadTest {
此时线程可以停止,但是在for循环外加上输出语句仍然可以输出
加上输出语句
public class ExceptionStopThread extends Thread {
@Overridepublic void run() {
super.run();
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println("Thread stop.");
break;
}
System.out.println("i = " + i);
}
System.out.println("outline loops, thread is not stop.");
}
}
解决问题方法,抛出异常
public class ExceptionStopThread extends Thread {
@Overridepublic void run() {
super.run();
try {
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println("Thread stop");
throw new InterruptedException();
}
System.out.println("i = " + i);
}
} catch (InterruptedException e) {
System.out.println("Catch InterruptedException");
e.printStackTrace();
}
}
}
return法:
public class ReturnStopThread extends Thread {
@Override
public void run() {
while (true) {
if (this.isInterrupted()) {
System.out.println("Thread is stop.");
return;
}
System.out.println("timer = " + System.currentTimeMillis());
}
}
}
public static void main(String[] args) {
ReturnStopThread thread = new ReturnStopThread();
thread.start();
try {
thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
thread.interrupt();
}
注:this.interrupted() : 测试当前线程是否已经是中断状态,执行后具有将状态标识清除为false的功能。
this.isInterrupted() : 测试线程Thread对象是否已经是中断状态,但不清除状态标志。
- 异常法和return法
- 【JVM】异常和return
- java异常处理中的return和throw
- 异常中的finally和方法中的return
- C# 异常处理-finally 和 return
- 有异常语句和return的执行
- java异常处理中的return和throw
- Java异常处理---finally和return的执行顺序
- 停止线程的两种方式(异常和Return)
- Java中异常处理-finally和return执行顺序
- 多线程基础四(二)、能停止的线程(异常法、sleep、return、interrupt、stop)
- finally+return+异常
- 异常,finally&&return
- 异常-catch中的return
- return、return true和return false
- return fause和return true
- return *this和return this
- return *this和return this
- idea加载maven包
- Linux ./configure --prefix 命令是什么意思?
- Grails的beforeInterceptor拦截器
- JavaScript从数组中删除指定值元素的方法
- Oracle Study之--Oracle 12c RAC install (二)
- 异常法和return法
- Java常用的八种排序算法与代码实现
- Java中的面试题 [6] --- Java前端知识、模板、css、jsp、ajax、JavaScript、vue.js等
- 离散数学学习网站
- java并发锁之Lock
- Volley源码解析(三)——NetworkDispatcher
- Ceph配置参数分析
- Spring实战学习(二)
- OpenCV人脸识别