Java中的線程 (Threading in Java)


問題描述

Java中的線程 (Threading in Java)

I am trying to have my main thread spawn off a new thread and, after some time, raise the interrupt flag. When it does so, the spawned thread should see that flag and terminate itself.

The main thread looks something like this:

final Thread t = new Thread()
{
    @Override
    public void run()
    {
        f();
    }
};
t.start();
try
{
    t.join(time);
    t.interrupt();
    if(t.isAlive())
    {
        t.join(allowance);
        if(t.isAlive())
            throw new Exception();
    }
}
catch(Exception e)
{
    System.err.println("f did not terminate in the alloted time");
}

And the spawned thread has a bunch of the following scattered throughout its code:

if(Thread.interrupted()) return;

When I am in debug mode, everything works perfectly. The interrupt flag is raised by the main thread and is caught by the spawned thread. However, in regular run mode the spawned thread doesn't seem to receive the interrupt flag, no matter how long I set the allowance.

Does anyone know what I am doing wrong?

Note: I am using Ubuntu and I am all‑together new to anything Linux. Can the problem be with the OS? I have not tested the code on any other OS.

‑‑‑‑‑

參考解法

方法 1:

Here are my guesses: 

  • When main thread calls t.interrupt(); the t thread has already finished execution. 
  • When main thread calls t.interrupt(); in the t thread there are no more calls to check interrupted() flag. 
  • You get the exception as a result of running the code? Do you get the exception you throw in your code after "allowance" time or you got some other like ThreadInterruptedException or similar? Try writing the message of the caught exception...

方法 2:

It looks as though the Thread.interrupted() call is not being reached in f(). 

The different behaviour you are seeing in Debug and Run modes is likely to be due to a race condition.

方法 3:

Do you have nested checks of Thread.interrupted()? That method clears the interrupted flag, so the second call returns false. You could use isInterrupted() instead.

方法 4:

I suggest you consider using an ExecutorService which is designed to do this sort of thing and could help you in other ways.

ExecutorService service = Executors.newCachedThreadPool();
Future<ResultType> future = service.submit(new Callable<ResultType() {
   public ResultType call() throws Exception {
      // do soemthing
      return (ResultType) ...;
   }
);
// do anything you like until you need to result.
try {
   ResultType result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException timedOut) {
  // handle exception
  // cancel the task, interrupting if still running.
  result.cancel(true);
} catch (ExecutionException taskThrewAnException) {
  // handle exception
}
// when you have finished with the service, which is reusable.
service.shutdown();

(by user108088emircMatthew MurdochStephen DennePeter Lawrey)

參考文件

  1. Threading in Java (CC BY‑SA 3.0/4.0)

#interrupt #java #multithreading






相關問題

無法在 java 命令行程序中捕獲中斷 (Unable to catch interrupt in java command line program)

不連續的 BitBlt 捕獲 (discontinuous BitBlt capture)

GPIO 更改狀態時如何更新 sysfs? (How is sysfs updated when a GPIO changes state?)

Linux IRQ 處理程序中的固有競爭條件 (Inherent race condition in Linux IRQ handlers)

STM32 外部中斷僅在調試模式下響應 (STM32 external interrupt responds only in debug mode)

Java中的線程 (Threading in Java)

如何在被 Python 殺死之前運行最後一個函數? (How to run one last function before getting killed in Python?)

在 C++ 中處理中斷 (Handling Interrupt in C++)

應用程序中斷瘋狂 (Application interrupts like crazy)

SetPriorityClass(REALTIME_PRIORITY_CLASS) 實際上做了什麼? (What does SetPriorityClass(REALTIME_PRIORITY_CLASS) actually do?)

如何找出軟件掛起的原因?(qemu + zephyr + tfm 的問題) (How to find out the cause of hanging software? (problem with qemu + zephyr + tfm))

將參數傳遞給系統調用 (Passing arguments to system calls)







留言討論