2014-09-08 2 views
0

고정 된 간격으로 UDP 패킷을 보내는 스레드가 있습니다. 잠시 후 나는 다른 스레드에서 interrupt()를 호출하고 있으며, 그 이후에는 완전히 보낸 스레드를 기다리고있다. 대부분의 경우, 송신기 스레드는 인터럽트를 수신 한 후에 마칩니다. 드문 경우지만, 보낸 사람 스레드는 그렇지 않습니다. 내 스레드 코드에서 실수를 발견하도록 도와 주시겠습니까? 나는 코드의 특정 부분에, 당신은 예외 : InterruptedException을 잡기 후 interruptedException.Restore에게 인터럽트를 삼키는 볼 수 있듯이스레드 인터럽트가 항상 작동하지 않는 경우

try { 
    DatagramSocket socket = null; 
    Timber.d("Initialize the sender..."); 

    while (!Thread.currentThread().isInterrupted()) { 
     try { 
      Timber.d("Sending UDP broadcasts..."); 
      socket = new DatagramSocket(); 

      while (!Thread.currentThread().isInterrupted()) { 
       String s = "hello"; 
       byte[] buffer = s.getBytes(); 
       DatagramPacket packet = new DatagramPacket(
         buffer, buffer.length, 
         mBroadcastAddress, PORT); 
       try { 
        if (BuildConfig.DEBUG) 
         Timber.d("[" + new DateTime().toLocalTime() + "] " + 
           "Send UDP packet"); 
        socket.send(packet); 
       } catch (IOException ioe) { 
        Timber.d(ioe, "IOException"); 
       } 
       Thread.sleep(TIMEOUT_SLEEP); 
      } 
     } catch (SocketException se) { 
      Timber.d(se, "Socket exception"); 
      break; 
     } finally { 
      if (socket != null) 
       socket.close(); 
      socket = null; 
     } 
    } 
} catch (InterruptedException ie) { 
    Timber.d("The sender thread received interrupt request"); 
} 

Timber.d("Finish the sender..."); 
+0

확실히 인터럽트가 호출되고 있습니까? –

답변

1

나는 문제가 여기에 있다고 생각 :

} catch (IOException ioe) { 
     Timber.d(ioe, "IOException"); 
    } 

문제는 ... IOException의 부속 유형 중 하나 인 것을 InterruptedIOException이다. 그리고 (인터럽트에 대한 응답으로) 예외가 발생하면 스레드의 interrupted 플래그가 지워집니다. 이제는 send 호출 중에이 코드가 중단 될 가능성은 거의 없습니다. 그러나 그렇다면 효과적으로 인터럽트를 먹을 것입니다. 나중에 인터럽트 플래그를 테스트하려는 경우

} catch (InterruptedIOException ioe) { 
     Thread.currentThread().interrupt(); 
    } catch (IOException ioe) { 
     Timber.d(ioe, "IOException"); 
    } 

또한이, 당신은 또한 "를 먹고"당신이에 InterruptedException를 잡을 때

나는 위의 변경해야한다고 생각 스 니펫의 끝 부분에서 다시 설정해야합니다.

+0

interrupt() 호출은 InterruptedException이 아닌 InterruptedException을 트리거한다고 생각했습니다. send() 메서드가 InterruptedException을 InterruptedException으로 Rethrows하는 것을 이해해야합니까? –

+1

사실,'interrupt()'는 반드시 예외 중 하나 *를 트리거하지 않습니다. IIRC는'InterruptedException'을 throw하는 sleep/wait/etc 메소드의 코드와'InterruptedIOException'을 던지는 IO 호출의 코드입니다. –

0

, 그것을 삼키지 않는다. 다음은 인터럽트를 복원하는 방법입니다. Thread.currentThread(). interrupt();

관련 문제