zoukankan      html  css  js  c++  java
  • Thread is suspended; attempting to abort的错误处理

    在自制线程池的过程中遇到这样一个情景:需要中断一个可能是正在执行的任务,这个任务也可能任务队列中,由于是线程池,任务执行完后线程不是消失的而是继续等待接收下一个任务的,我使用的是Thread.Suspend来暂停线程当线程完成一项任务后,这时候如果使用Thread.Abort来中断这个ThreadState为Suspended的线程是会报错的。

    以下代码重现了我的错误

    Code

    google许久,发现一篇英文http://www.code-magazine.com/article.aspx?quickid=0309071&page=4描述的非常清楚,其中有如下一段:

    If Abort() is called before the thread is started, .NET will never start the thread once Thread.Start() is called. If Thread.Abort() is called while the thread is blocked (either by calling Sleep(), or Join(), or if the thread is waiting on one of the .NET synchronization objects), .NET unblocks the thread and throws ThreadAbortException in it. However, you cannot call Abort() on a suspended thread. Doing so will result on the calling side with an exception of type ThreadStateException, with the error message "Thread is suspended; attempting to abort." In addition, .NET will terminate the suspended thread without letting it handle the exception

    就是说线程的状态是Suspended的时候,是不能使用Thread.Abort来中止的,那我们的情况怎么处理呢,我们换了一个思路,既然线程的状态已经是 Suspended了为什么我们还要Abort它呢,将它再次放入线程池为后续任务工作不是更好吗?

    于是加一个条件判断

    if(Thread.ThreadState==ThreadState.Suspended):
           pass

    这样就ok了

  • 相关阅读:
    查看Java中每个数据类型所占的位数,和表示数值的范围,并得出结论。
    同名变量的屏蔽原则
    反码,补码,原码
    机器学习概念性知识总结
    图的最短路径问题
    System Design 笔记及代码(系统设计)
    2016网易游戏实习算法题解(今年找暑期实习的时候参加的)
    Google java style
    18.1---不用加号的加法(CC150)
    Java模板模式(template)
  • 原文地址:https://www.cnblogs.com/lexus/p/1263283.html
Copyright © 2011-2022 走看看