在中断线程时设置中断原因

时间:2022-03-22 19:34:58

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.

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

  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. 用于设置超时的标志和IO错误的另一个标志(因为我的主程序很大并且有几个部分,我无法在任何地方进行检查)

  3. 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).
  4. 每个线程都有一个成员变量设置状态代码,主程序读取中断。(我很好,但我仍然需要维护线程对象来获取状态,我的文件读取器线程很多,所以我必须迭代每个线程以找到被中断的一个)。

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

我很感激你的帮助,即使是中断以外的其他方式也没关系。

1 个解决方案

#1


0  

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:

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

IOException ioex;

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

#1


0  

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:

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

IOException ioex;

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