首页

关于java.lang.ThreadDeath线程发生场景及模拟代码测试ThreadDeathTest示例代码

标签:ThreadDeath,线程死亡,线程强制停止,强制解锁,Throwable,Error,异常错误     发布时间:2018-10-20   

一、前言

在java中虚拟机运行时,强制将运行的线程停止(this.stop())或对于锁定的对象强制"解锁"两种场景,造成数据不一致,这是会抛出java.lang.ThreadDeath线程死亡java.lang.Error错误,详情参见代码示例部分。

二、代码示例

package test;@b@@b@public class ThreadDeathTest {@b@	@b@	private  static  Thread theadDemo;@b@@b@	public static void main(String[] args)  throws  Exception{@b@		@b@		theadDemo=new Thread(new Runnable() {@b@			@Override@b@			public void run() {@b@				 try {@b@					 try {@b@						 theadDemo.stop();@b@					} catch (ThreadDeath  e) {@b@						System.out.println("ThreadDeath模拟异常已经发生!!!");@b@						e.printStackTrace();@b@					}@b@				} catch (Exception e) {@b@					e.printStackTrace();@b@				}  @b@			}@b@		});@b@		@b@		theadDemo.start();@b@	}@b@@b@}

控制台结果

ThreadDeath模拟异常已经发生!!!@b@java.lang.ThreadDeath@b@	at java.lang.Thread.stop(Thread.java:758)@b@	at test.ThreadDeathTest$1.run(ThreadDeathTest.java:14)@b@	at java.lang.Thread.run(Thread.java:662)