从头认识多线程-1.7 迫使线程停止的方法-错误法的扩展(Sleep的Exception)
从头认识多线程-1.7 迫使线程停止的方法-异常法的扩展(Sleep的Exception)
这一章节我们来讨论一下异常法的扩展Sleep的Exception。
1.使用情景
有些时候我们使用多线程执行一项任务,但是我们会对这个任务的进行时间进行评估,任务某个值之后就是超时,这个时候必须终止任务,并返回信息给客户
2.代码清单
package com.ray.deepintothread.ch01.topic_7; public class StopBySleep { public static void main(String[] args) throws InterruptedException { ThreadFive threadFive = new ThreadFive(); threadFive.start(); Thread.sleep(200); threadFive.interrupt(); } } class ThreadFive extends Thread { @Override public void run() { System.out.println("------------begin-------------"); try { System.out.println("------------working-------------"); sleep(2000); } catch (InterruptedException e) { System.out.println("------------exit-------------"); } super.run(); } }
------------begin-------------
------------working-------------
------------exit-------------
从代码和输出那里可以看到,当前任务执行的时间是2秒,但是我们认为200毫秒的运行就已经算是超时,这个时候我们必须停止线程,然后给用户返回信息。
总结:这一章节主要对异常法进行扩展,通过对sleep方法的异常抛出,来作为终止线程的一种方式。
我的github:https://github.com/raylee2015/DeepIntoThread