中断线程时设置中断原因

发布于 2024-10-19 12:33:10 字数 398 浏览 1 评论 0原文

感谢您的所有帮助和支持,我面临一个问题,我有两个线程,一个是计时器线程,另一个是某个文件读取器线程。现在我的主程序正在调用两个线程。计时器线程在超时时中断主程序,如果出现一些 IO 错误,文件读取器线程将调用主线程。所以现在问题出现了,主程序必须知道谁触发了中断,以便打印一些中断状态。那么我该如何实现这一目标呢?下面是一些我不想使用的东西。

  1. 一个用于设置超时的标志和另一个用于 IO 错误的标志(因为我的主程序很大并且有几个部分,我不能在任何地方都进行此检查)
  2. 每个线程都有一个设置有状态代码的成员变量,并且主程序读取(我对此表示同意,但我仍然需要维护线程对象来获取状态,并且我的文件读取器线程很多,所以我必须迭代每个线程以找到中断的线程)。

我将不胜感激您对此的帮助,即使除了中断之外的其他方式也可以。

Thanks for all the help and support , I am facing a problem where by i have two threads one is a Timer thread , and another one is some File Reader thread. Now my main program is calling both the threads. The timer thread interrupts the main program on timeout , and the File Reader thread invokes the main thread if there are some IO errors. So now the problem steps in , the Main program has to know who has fired the interrupt , to print some interrupt status lets say. So how do i acheive this? Below are few things i dont want to use.

  1. A flag which is used to set on Timeout and another flag for IO error (Because My main program is huge and has several parts and i cant do this check everywhere)
  2. Each thread having a member variable set with status code , and the main program reading that on interrupt.(I am ok with this, but i still need to maintain the thread objects to get the status , and my File Reader threads are many , so i have to iterate every thread to find the one interrupted).

I would appreciate your help on this , even some other way other than interrupts is also fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好菇凉咱不稀罕他 2024-10-26 12:33:10

我通过声明 Exception 变量来做到这一点,然后如果等待线程获得设置了 Exception 变量的中断,则重新抛出异常:

IOException ioex;

synchronized(lockObject) {
    while( true ) {
        try {
            lockObject.wait();
        } catch( InterruptedException e ) {
            if( ioex != null ) { 
                throw ioex;
            }
        }
        ... normal handling ...
    }
}

I do it by declaring an Exception variable, and then I rethrow the exception if the waiting thread gets an interrupt which the Exception variable is set:

IOException ioex;

synchronized(lockObject) {
    while( true ) {
        try {
            lockObject.wait();
        } catch( InterruptedException e ) {
            if( ioex != null ) { 
                throw ioex;
            }
        }
        ... normal handling ...
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文