A method of feeling thread interrupt (original)

xiaoxiao2021-03-06  126

The day date studied the Java thread problem. I found that many books did not mention the interrput () method. It also mentioned that the thread interrupt cannot be implemented using the interrupt () method, but after my constant trial, I use an interrupt () method and isInterrupted. () The method implements the interruption of the thread. If this method can, in addition to using shared variables, there is a way to interrupt the thread, and it is hoped that this method is helpful.

Class threada extends thread {int count = 0; public void run () {system.out.println (getName () "will run ..."); while (! this.isinterrupted ()) {system.out.println (GetName () "run" count ); try {thread.sleep (400); // Sleep 400 milliseconds} Catch (InterruptedException E) {// Exit the blocking state When the abnormal system.out.println is captured (GetName) () "Exit from the blocking state ..."); this.interrupt (); // change the thread state, end the loop to end}} system.out.println (getName () "has terminated!");} } Class threadDemo134 {public static void main (string argv []) throws interruptedException {threada ta = new threada (); ta.setname ("threada"); ta.start (); thread.sleep (2000); // Thread sleep 2000 milliseconds, waiting for other threads to execute System.out.Println (TA.Getnam e () "is interrupted ....."); ta.interrupt (); // Interrupt thread threada}}

Program operation results in album

转载请注明原文地址:https://www.9cbs.com/read-125921.html

New Post(0)