Stop停止线程:
使用stop()方法停止线程是非常暴力的,会抛出java.lang.ThreadDeath Error,但是我们无需显示捕捉, 以下捕捉只是为了看得更清晰。
public class StopThread extends Thread{ private int i = 0; @Override public void run() { try { while(true) { i++; System.out.println("i= " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Stop thread. Interrupted status: " + this.isInterrupted()); e.printStackTrace(); } catch (Error e){ System.out.println("Enter error. Interrupted status: " + this.isInterrupted()); e.printStackTrace(); } } } public class ThreadRunMain { public static void main(String[] args) { testStopThread(); } public static void testStopThread(){ try { StopThread st = new StopThread(); st.start(); Thread.sleep(5000); st.stop(); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果:
stop()方法已经被作废,因为如果暴力让线程停止可能会使一些清理性的工作得不到完成。其次,可能会造成数据不一致的问题。如下例:
public class SynchronizedObject { private String username = "a"; private String password = "aa"; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } synchronized public void printString(String username, String password){ try { this.username = username; Thread.sleep(100000); this.password = password; } catch (InterruptedException e) { e.printStackTrace(); } } } public class StopThreadIssue extends Thread{ private SynchronizedObject object; public StopThreadIssue(SynchronizedObject object) { super(); this.object = object; } @Override public void run() { object.printString("b", "aa"); } } public class ThreadRunMain { public static void main(String[] args) { testStopThreadIssue(); } public static void testStopThreadIssue(){ try { SynchronizedObject object = new SynchronizedObject(); StopThreadIssue sti = new StopThreadIssue(object); sti.start(); Thread.sleep(500); sti.stop(); System.out.println(object.getUsername() + " " + object.getPassword()); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果:
我们期望的结果应该是:b bb,可是由于强制停止,导致 this.password = password; 没有执行。显然stop()在功能上具有缺陷,所以不建议在程序中使用stop()方法。