调用stop方法时会抛出java.lang.ThreadDeath异常,但一般情况下这个异常不需要显示的捕捉
package com.cky.thread; /**
* Created by edison on 2017/12/3.
*/
public class MyThread extends Thread{
@Override
public void run() {
super.run();
try {
this.stop();
} catch (ThreadDeath e) {
e.printStackTrace();
}
}
}
package com.cky.test; import com.cky.thread.MyThread; /**
* Created by edison on 2017/12/3.
*/
public class Test {
public static void main(String[] args) {
MyThread th = new MyThread();
th.start();
}
}
C:\itsoft\jdk\bin\java -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\itsoft\idea\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\itsoft\jdk\jre\lib\charsets.jar;C:\itsoft\jdk\jre\lib\deploy.jar;C:\itsoft\jdk\jre\lib\ext\access-bridge-32.jar;C:\itsoft\jdk\jre\lib\ext\cldrdata.jar;C:\itsoft\jdk\jre\lib\ext\dnsns.jar;C:\itsoft\jdk\jre\lib\ext\jaccess.jar;C:\itsoft\jdk\jre\lib\ext\jfxrt.jar;C:\itsoft\jdk\jre\lib\ext\localedata.jar;C:\itsoft\jdk\jre\lib\ext\nashorn.jar;C:\itsoft\jdk\jre\lib\ext\sunec.jar;C:\itsoft\jdk\jre\lib\ext\sunjce_provider.jar;C:\itsoft\jdk\jre\lib\ext\sunmscapi.jar;C:\itsoft\jdk\jre\lib\ext\sunpkcs11.jar;C:\itsoft\jdk\jre\lib\ext\zipfs.jar;C:\itsoft\jdk\jre\lib\javaws.jar;C:\itsoft\jdk\jre\lib\jce.jar;C:\itsoft\jdk\jre\lib\jfr.jar;C:\itsoft\jdk\jre\lib\jfxswt.jar;C:\itsoft\jdk\jre\lib\jsse.jar;C:\itsoft\jdk\jre\lib\management-agent.jar;C:\itsoft\jdk\jre\lib\plugin.jar;C:\itsoft\jdk\jre\lib\resources.jar;C:\itsoft\jdk\jre\lib\rt.jar;C:\多线程核心技术\第一章\out\production\第一章;C:\itsoft\idea\IntelliJ IDEA 2016.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.cky.test.Test
java.lang.ThreadDeath
at java.lang.Thread.stop(Thread.java:853)
at com.cky.thread.MyThread.run(MyThread.java:12) Process finished with exit code 0
方法stop已经作废
因为如果强制让线程停止则会使得一些清理性的工作得不到完成,另外一个就是对锁定对象进行解锁,导致数据得不到同步处理,出现数据不一致。