11package InterruptingThreads14 ;
22
3- import java .util .Random ;
4- import java .util .concurrent .Callable ;
5- import java .util .concurrent .ExecutorService ;
6- import java .util .concurrent .Executors ;
7- import java .util .concurrent .Future ;
8- import java .util .concurrent .TimeUnit ;
3+ import java .util .concurrent .*;
94
105/**
11- * how to interrupt running threads in Java using the built-in thread
12- * interruption mechanism.
13- *
14- * Source:http://www.javamex.com/tutorials/threads/thread_interruption.shtml
15- * Incidentally, it is important not to confuse thread interruption with either
6+ * <b>How to interrupt running threads in Java using the built-in thread
7+ * interruption mechanism.</b>
8+ * <br><br>
9+ * Source:
10+ * <a href="http://www.javamex.com/tutorials/threads/thread_interruption.shtml">
11+ * http://www.javamex.com/tutorials/threads/thread_interruption.shtml</a>
12+ * <p>
13+ * Incidentally, it is important NOT to confuse thread interruption with either
1614 * software interrupts (where the CPU automatically interrupts the current
1715 * instruction flow in order to call a registered piece of code periodically— as
1816 * in fact happens to drive the thread scheduler) and hardware interrupts (where
1917 * the CPU automatically performs a similar task in response to some hardware
2018 * signal).
21- *
22- * Codes with minor comments are from http://www.caveofprogramming.com/youtube/
19+ * <br><br>
20+ * Codes with minor comments are from
21+ * <a href="http://www.caveofprogramming.com/youtube/">
22+ * <em>http://www.caveofprogramming.com/youtube/</em>
23+ * </a>
24+ * <br>
2325 * also freely available at
24- * https://www.udemy.com/java-multithreading/?couponCode=FREE
26+ * <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
27+ * <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
28+ * </a>
2529 *
2630 * @author Z.B. Celik <[email protected] > 2731 */
@@ -37,20 +41,30 @@ public static void main(String[] args) throws InterruptedException {
3741
3842 @ Override
3943 public Void call () throws Exception {
40- Random ran = new Random ();
44+
4145 for (int i = 0 ; i < 1E8 ; i ++) {
4246 if (Thread .currentThread ().isInterrupted ()) {
43- System .out .println ("Interrupted!" );
47+ System .out .printf ("Interrupted at %d !!!" , i );
4448 break ;
4549 }
46- Math .sin (ran .nextDouble ());
4750 }
51+
4852 return null ;
4953 }
5054 });
5155
5256 executor .shutdown ();
5357 Thread .sleep (500 );
58+
59+ /*
60+ in this example, there are different ways you can interrupt a thread
61+ execution.
62+ */
63+
64+ //JavaDoc: http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#cancel-boolean-
65+ // fu.cancel(true);
66+
67+ //JavaDoc: http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow--
5468 executor .shutdownNow ();
5569
5670 executor .awaitTermination (1 , TimeUnit .DAYS );
0 commit comments