java 多线程 return_《Java多线程编程核心技术(第2版)》 —1.11.8 使用“return;”语句停止线程的缺点与解决方案...

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所示。

1581146569774972.png

图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块中被统一处理了,代码风格更加标准。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值