11

Fondamentalmente, cosa dice il titolo della domanda.La chiamata a Thread.interrupt() prima di Thread.join() fa sì che il join() lanci immediatamente una InterruptedException?

Thread t = new Thread(someRunnable); 
t.start(); 
t.interrupt(); 
t.join(); //does an InterruptedException get thrown immediately here? 

Dalle mie prove, sembra, ma volevo essere sicuro. Sto indovinando Thread.join() controlla lo stato interrupted della discussione prima di eseguire la sua routine di "attesa"?

+2

No, Thread.join() riguarda solo interruzioni del thread * current *. – EJP

risposta

14

interrupt() interrompe il thread interrotto, non il thread che interrompe.

c.f.

Thread.currentThread().interrupt(); 
t.join(); // will throw InterruptedException 
14

Vuol chiamare Thread.interrupt() prima di un Thread.join() causa il join() per buttare subito un InterruptedException?

No, non gettare. Solo se il thread corrente che sta chiamando il metodo viene interrotto, il numero join() verrà lanciato InterruptedException. t.interrupt() interrompe il thread appena avviato, mentre t.join() getterà solo InterruptedException se il thread che sta facendo il join (forse il thread principale?) Viene interrotto.

Thread t = new Thread(someRunnable); 
t.start(); 
t.interrupt(); 
t.join(); // will _not_ throw unless this thread calling join gets interrupted 

Inoltre è importante rendersi conto che l'interruzione di un filo non l'annulla ejoin() non è come un Future in che restituisca l'eccezione del filo gettato.

Quando si interrompe un thread, chiamate il thread sta facendo per sleep(), wait(), join() e altri metodi interrompibili getteranno InterruptedException. Se questi metodi non vengono chiamati, il thread continuerà a essere eseguito. Se un thread fa lancia un InterruptedException in risposta all'interruzione e quindi si chiude, quell'eccezione si perderà a meno che non si sia utilizzato t.setDefaultUncaughtExceptionHandler(handler).

Nel tuo caso, se il thread è interrotto e termina perché ritorna, quindi il join termina - non genererà un'eccezione. Il codice di thread comune per gestire correttamente un interrupt è il seguente:

public void run() { 
    try { 
     Thread.sleep(10000); 
    } catch (InterruptedException e) { 
     // a good pattern is to re-interrupt the thread when you catch 
     Thread.currentThread().interrupt(); 
     // another good pattern is to make sure that if you _are_ interrupted, 
     // that you stop the thread 
     return; 
    } 
}