调用stop方法时会抛出java.lang.ThreadDeath异常,但一般情况下这个异常不需要显示的捕捉
1 package com.cky.thread; 2 3 /** 4 * Created by edison on 2017/12/3. 5 */ 6 public class MyThread extends Thread{ 7 @Override 8 public void run() { 9 super.run(); 10 try { 11 this.stop(); 12 } catch (ThreadDeath e) { 13 e.printStackTrace(); 14 } 15 } 16 }
1 package com.cky.test; 2 3 import com.cky.thread.MyThread; 4 5 /** 6 * Created by edison on 2017/12/3. 7 */ 8 public class Test { 9 public static void main(String[] args) { 10 MyThread th = new MyThread(); 11 th.start(); 12 } 13 }
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已经作废
因为如果强制让线程停止则会使得一些清理性的工作得不到完成,另外一个就是对锁定对象进行解锁,导致数据得不到同步处理,出现数据不一致。
时间: 2024-11-08 20:29:09