How do you kill a Thread in Java?

前端 未结 16 2040
天命终不由人
天命终不由人 2020-11-21 05:54

How do you kill a java.lang.Thread in Java?

16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 06:52

    There is of course the case where you are running some kind of not-completely-trusted code. (I personally have this by allowing uploaded scripts to execute in my Java environment. Yes, there are security alarm bell ringing everywhere, but it's part of the application.) In this unfortunate instance you first of all are merely being hopeful by asking script writers to respect some kind of boolean run/don't-run signal. Your only decent fail safe is to call the stop method on the thread if, say, it runs longer than some timeout.

    But, this is just "decent", and not absolute, because the code could catch the ThreadDeath error (or whatever exception you explicitly throw), and not rethrow it like a gentlemanly thread is supposed to do. So, the bottom line is AFAIA there is no absolute fail safe.

提交回复
热议问题