java - Thread.interrupt() Confusion -


i reading interrupts oracle docs. unable figure out following part. states that

what if thread goes long time without invoking method throws interruptedexception? must periodically invoke thread.interrupted, returns true if interrupt has been received. example:

for (int = 0; < inputs.length; i++) {     heavycrunch(inputs[i]);     if (thread.interrupted()) {         // we've been interrupted: no more crunching.         return;     } } 

i scratching head understand, mean if thread goes long time without invoking method throws interruptedexception? secondly, usage of thread.interrupted(), way, thread can send interrupt itself? whats practical usage of scenario? thanks.

this technique keep thread available interruption.

thread.interrupted() : checks whether present thread (itself) interrupted other thread , clears interrupted status flag. asks whether interrupted exit doing while performing big big task , not listening someone.

imagine have happened if thing not done.

suppose 1 iteration of heavycrunch() takes 1 min worth of time. n iterations take n minutes.

now suppose after starting program decide want exit program , terminate program gracefully. interrupt thread doing heavy crunch. thread unknown of fact have interrupted not checking interrupt status. program not end until n minutes have not completed , have wait long time.

so gracefully terminate thread, should keep checking interrupt status respond if else has requested interruption.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -