Thread类有一个方法 stop. 已经被禁用 当你使用stop()时,程序会强制中断进程并立即退出,那么这时候就会立即释放锁,这时候就会出现读写混乱 如下程序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.longfor.dragonshard.service.cost.standard.impl; public class StopThreadUnsafe { public static User user = new User(); public static class User{ private int id; private String name; public User(){ id=0; name="0"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } } public static class ChangeObjectThread extends Thread{ private volatile boolean stopme = false; public void stopMe(){ stopme = true; } @Override public void run() { while (true){ if (stopme==true){ break; } synchronized (user){ int u = (int)(System.currentTimeMillis()/1000); user.setId(u); try { Thread.sleep(100); }catch (Exception e){ e.printStackTrace(); } user.setName(String.valueOf(u)); } Thread.yield(); } } } public static class ReadObjectThread extends Thread{ @Override public void run() { while (true){ synchronized (user){ if (user.getId() != Integer.parseInt(user.getName())){ System.out.println(user.toString()); } } Thread.yield(); } } } public static void main(String[] args) throws Exception{ new ReadObjectThread().start(); while (true){ ChangeObjectThread thread = new ChangeObjectThread(); thread.start(); Thread.sleep(100); thread.stop(); } } }
所以我们自己设置中断条件 而不是用stop Java自己也有设置中断条件
interrupt() 设置中断状态
isInterrupt() 判断是否中断
interrupted() 判断是否中断 并清除中断状态
设置中断状态实际上是向程序发送一个通知 有人希望你结束进程 那么操作完全由程序自己控制 如果程序立即退出 那么就又相当于stop 所以我们要增加中断处理代码
如果我们不增加中断代码 只是增加中断状态 那么程序还是由程序自己控制 而不是我们
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.longfor.dragonshard.service.cost.standard.impl; public class Interrupt { public static void main(String[] args) throws InterruptedException{ MyThread thread = new MyThread(); thread.start(); Thread.sleep(1000); thread.interrupt(); } public static class MyThread extends Thread{ @Override public void run() { while (true){ if (Thread.currentThread().isInterrupted()){ System.out.println("this thread is interrupted.."); break; } Thread.yield(); } } } }
当我们使用sleep时 程序会抛出中断 那么我们捕获它 一旦捕获 那么中断状态就会清除 所以我们在加上中断状态
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.longfor.dragonshard.service.cost.standard.impl; public class SleepInterrupt { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); myThread.interrupt(); } public static class MyThread extends Thread{ @Override public void run() { while (true){ if (Thread.currentThread().isInterrupted()){ System.out.println("this thread is interrupted..."); break; } try { Thread.sleep(2000); }catch (InterruptedException e){ System.out.println(e.getMessage()); Thread.interrupted(); } Thread.yield(); } } } }