Java线程:关闭标志与捕获异常
发布时间:2020-12-15 04:54:31 所属栏目:Java 来源:网络整理
导读:在处理取消时的线程中,您经常会看到这样的代码 while (!shutdown) { .. do something,if a blocking call,then it will throw the interrupted exception try { .. some more ... } catch (InterruptedException e) { shutdown = true; }} 我想知道的是,这是
在处理取消时的线程中,您经常会看到这样的代码
while (!shutdown) { .. do something,if a blocking call,then it will throw the interrupted exception try { .. some more ... } catch (InterruptedException e) { shutdown = true; } } 我想知道的是,这是为什么,或者为什么这样做,比这更好 try { while (true) { .. do something,then it will throw the interrupted exception if (Thread.interrupted()) throw new InterruptedException(); } } catch (InterruptedException e) { .. clean up,let thread end } 我看到它的方式是,在后一种情况下,你根本不需要打扰关闭var. 解决方法
你不使用异常作为退出条件的方法(至少不是典型的,这是一种最好避免的做法.)一个例外是… cue鼓…宣布例外,错误,情况和通常或可能不好的条件.
关闭不是(通常)错误条件,所以至少从哲学/设计的角度来看,我更喜欢使用shutdown flag变量的第一个选项. 此外,该标志可以外部化为只读属性(例如,作为getter).然后线程外部的组件可以查看线程是否仍然处于活动状态(如果它们具有合法依赖于该逻辑的逻辑.) 在个人方面,我不喜欢Java使用InterruptedException,因为它通常不是每个例外的例外,而是信号,通常是正常和预期的信号.那好吧. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |