Java 仅当处于临界段时才中断另一个线程
我有一个在线程中运行的方法,我只希望该线程在给定的关键方法/节中被中断。如果中断,将从具有未定义行为的旧代码调用该方法 如何设置关键方法和中断器方法,使中断不会将代码留在遗留代码中 我尝试过使用睡眠和其他技术来减少比赛条件,但没有一种能完全消除它们Java 仅当处于临界段时才中断另一个线程,java,multithreading,interrupt,race-condition,Java,Multithreading,Interrupt,Race Condition,我有一个在线程中运行的方法,我只希望该线程在给定的关键方法/节中被中断。如果中断,将从具有未定义行为的旧代码调用该方法 如何设置关键方法和中断器方法,使中断不会将代码留在遗留代码中 我尝试过使用睡眠和其他技术来减少比赛条件,但没有一种能完全消除它们 public class InterruptPlayground { Thread _thread = null; /** * Implements some interface that legacy calls on "ma
public class InterruptPlayground
{
Thread _thread = null;
/**
* Implements some interface that legacy calls on "main" thread
*/
void methodCalledFromLegacyCode()
{
try // critical section (probably wrong term)
{
_thread = Thread.currentThread();
/**
* Lots of fancy code goes here...
*
* If we are in here this section, we want the method below to be able to interrupt us, to inform us of its
* impending death.
*/
}
finally
{
_thread = null; // part 1 of race
if (Thread.interrupted()) // part 3 of race
{
// consume any interrupts in attempt to prevent race conditions, and prevent legacy code from getting interrupt
}
}
/**
* If the other thread interrupts us after this, the legacy code would encounter it, and how it deals with
* interrupts is undefined (very legacy code, like 2000).
*/
}
/**
* Called when one of our threads is about to die and we need to inform the above method
*/
void methodThatNeedsToInterruptAboveMethod()
{
try
{
// if I did a null check, I could get a race condition, right?
_thread.interrupt(); // part 2 of race
}
catch (NullPointerException ex)
{
// guess we were not in the critical section
}
}
}
这个代码不受比赛条件限制吗?
从第二个方法调用的中断信号是否可能逃逸第一个方法(并到达遗留代码)?
我担心第1-3部分之间的竞争条件。在java中,这不是处理竞争条件的方法。您应该使用诸如“synchronized”、互斥体、信号量等语言特性。当多个线程访问共享状态时,可能无法看到彼此对该状态的更改。我在这里看不到这些。如果在方法末尾处理一个中断并重置中断标志(Thread.interrupted()),调用代码就不会知道它被中断了。就这么简单。除非我误解了你的目标。