Java中如何详细实现线程安全停止操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计359个文字,预计阅读时间需要2分钟。
`Thread.stop()` 是一个被废弃的方法,不推荐使用。原因在于 stop 方法过于粗暴,会强制将线程执行到一半终止,并立即释放线程持有的所有锁。这会破坏线程中使用的对象的原子性。
Thread.stop()是一个被废弃的方法,不被推荐使用的原因是stop方法太过于暴力,强行把执行到一半的线程终止,并且会立即释放这个线程所有的锁。会破坏了线程中引用对象的一致性。
使用判断标志位的方法中断线程
- interrupt() //线程中断 (标志位设置为true)
- isInterrupted() //判断是否被中断
- interrupted() //判断是否中断,并清除当前中断状态(标志位改为false)
public static class TestThread extends Thread{ public TestThread(String name){ super(name); } @Override public void run() { String threadName=Thread.currentThread().getName(); while (!isInterrupted()){ //Runnable中用 Thread.currentThread().isInterruputed System.out.println(threadName+" is run"); } System.out.println(threadName+" flag is "+isInterrupted()); } } public static void main(String[] args) throws InterruptedException { Thread testThread=new TestThread("test"); testThread.start(); Thread.sleep(2000); testThread.interrupt(); }
当抛出 InterruptedException 异常,线程中断标志位会被复位 false, 线程不会正常中断 ,需要手动中断interrupt()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。
本文共计359个文字,预计阅读时间需要2分钟。
`Thread.stop()` 是一个被废弃的方法,不推荐使用。原因在于 stop 方法过于粗暴,会强制将线程执行到一半终止,并立即释放线程持有的所有锁。这会破坏线程中使用的对象的原子性。
Thread.stop()是一个被废弃的方法,不被推荐使用的原因是stop方法太过于暴力,强行把执行到一半的线程终止,并且会立即释放这个线程所有的锁。会破坏了线程中引用对象的一致性。
使用判断标志位的方法中断线程
- interrupt() //线程中断 (标志位设置为true)
- isInterrupted() //判断是否被中断
- interrupted() //判断是否中断,并清除当前中断状态(标志位改为false)
public static class TestThread extends Thread{ public TestThread(String name){ super(name); } @Override public void run() { String threadName=Thread.currentThread().getName(); while (!isInterrupted()){ //Runnable中用 Thread.currentThread().isInterruputed System.out.println(threadName+" is run"); } System.out.println(threadName+" flag is "+isInterrupted()); } } public static void main(String[] args) throws InterruptedException { Thread testThread=new TestThread("test"); testThread.start(); Thread.sleep(2000); testThread.interrupt(); }
当抛出 InterruptedException 异常,线程中断标志位会被复位 false, 线程不会正常中断 ,需要手动中断interrupt()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

