In this chapter we will discuss thread break (interrupt).
1. What is thread interruption (interrupt)?
It is in the multi-threaded execution that we attach a broken tag to the thread. However, thread termination is not required.
2. Examples:
Examples of interrupts:
Package Com.ray.ch17;public class Test2 {public static void main (string[] args) {PrintA PrintA = new PrintA (); Thread Threada = new Thread (PrintA); Threada.start ();}} Class PrintA implements Runnable {private static int i = 0; @Overridepublic void Run () {while (! Thread.CurrentThread (). isinterrupted ()) {System.out.println ("PrintA"), if (i = = 2) {Thread.CurrentThread (). Interrupt ();} i++;}}}
Output:
PrintA
PrintA
PrintA
Examples of non-disruptive:
Package Com.ray.ch17;public class Test2 {public static void main (string[] args) {PRINTB printb = new Printb (); Thread threadb = new Thread (PRINTB); Threadb.start ();}} Class Printb implements Runnable {@Overridepublic void Run () {for (int i = 0; i < 5; i++) {System.out.println ("PRINTB") ; Thread.CurrentThread (). interrupt ();}}}
Output:
Printb
Printb
Printb
Printb
Printb
From the two examples above, we can see that the interrupt is simply affixed with an interrupt mark and will not be forced to break.
3.interrupt clash with Sleep
Because when used with sleep after interrupt, sleep will remove the interrupt mark
The conflict code. The following code will be output indefinitely:
Package Com.ray.ch17;public class Test2 {public static void main (string[] args) {PrintA PrintA = new PrintA (); Thread Threada = new Thread (PrintA); Threada.start ();}} Class PrintA implements Runnable {private static int i = 0; @Overridepublic void Run () {while (! Thread.CurrentThread (). isinterrupted ()) {System.out.println ("PrintA"), if (i = = 2) {Thread.CurrentThread (). Interrupt (); try {thread.currentthread (). Sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} i++;}}}
Summary: This chapter focuses on threading interrupts (interrupt).
This chapter is here, thank you.
-----------------------------------
Folder
Understanding java-17.2 thread interrupts from scratch (interrupt)