《Java多线程编程核心技术(第2版)》 —1.11.8 使用“return;”语句停止线程的缺点与解决方案
【摘要】 本节书摘来自华章计算机《Java多线程编程核心技术(第2版)》 一书中第1章,第1.11.8节,作者是高洪岩。
1.11.8 使用“return;”语句停止线程的缺点与解决方案
将interrupt()方法与“return;”语句结合使用也能实现停止线程的效果。
创建测试用的项目useReturnInterrupt,线程类MyThread.java代码如下:
package extthread;
public class MyThread extends Thread {
@Override
public void run() {
while (true) {
if (this.isInterrupted()) {
System.out.println("停止了!");
return;
}
System.out.println("timer=" + System.currentTimeMillis());
}
}
}
运行类Run.java代码如下:
package test.run;
import extthread.MyThread;
public class Run {
public static void main(String[] args) throws InterruptedException {
MyThread t=new MyThread();
t.start();
Thread.sleep(2000);
t.interrupt();
}
}
程序运行结果如图1-53所示。
图1-53 成功停止线程
虽然使用“return;”较“抛异常”法在代码结构上可以更加方便地实现线程的停止,不过还是建议使用“抛异常”法,因为在catch块中可以对异常的信息进行统一的处理,例如,使用“return;”来设计代码:
public class MyThread extends Thread {
@Override
public void run() {
// insert操作
if (this.interrupted()) {
System.out.println("写入log info");
return;
}
// update操作
if (this.interrupted()) {
System.out.println("写入log info");
return;
}
// delete操作
if (this.interrupted()) {
System.out.println("写入log info");
return;
}
// select操作
if (this.interrupted()) {
System.out.println("写入log info");
return;
}
System.out.println("for for for for for");
}
}
在每个“return;”代码前都要搭配一个写入日志的代码,这样会使代码出现冗余,不利于代码的阅读与扩展,这时可以使用“抛异常”法来简化这段代码:
public class MyThread2 extends Thread {
@Override
public void run() {
try {
// insert操作
if (this.interrupted()) {
throw new InterruptedException();
}
// update操作
if (this.interrupted()) {
throw new InterruptedException();
}
// delete操作
if (this.interrupted()) {
throw new InterruptedException();
}
// select操作
if (this.interrupted()) {
throw new InterruptedException();
}
System.out.println("for for for for for");
} catch (InterruptedException e) {
System.out.println("写入log info");
e.printStackTrace();
}
}
}
写入日志的功能在catch块中被统一处理了,代码风格更加标准。
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)