The thread object. Interrupt ()
Note that there is a break in the exception analysis, otherwise it cannot be interrupted
Public classDemoextendsJFrame {PrivateThread thread;//Defining Threads FinalJProgressBar ProgressBar =NewJProgressBar ();//progress bar PublicDemo () {setbounds (100, 100, 200, 100); Setdefaultcloseoperation (Windowconstants.exit_on_close); Getcontentpane (). Add (ProgressBar, Borderlayout.north); Progressbar.setstringpainted (true);//Show Numbers//implementing thread objects using anonymous inner classesThread =NewThread () {intCount = 0;//Progress Data Public voidrun () { while(true) {//infinite loops, typically used when the number of cycles is not knownProgressbar.setvalue (+ +)count); if(Count = = 20) { //Thread.Interrupt (); This. Interrupt (); } Try{Thread.Sleep (100);//Sleep 0.1s}Catch(interruptedexception e) {e.printstacktrace (); System.out.println ("20% were interrupted");//Throw Exception Break;//there must be a break, otherwise it cannot be interrupted } } } }; Thread.Start (); SetVisible (true); } Public Static voidMain (string[] args) {NewDemo (); }}
The interrupt for the thread. Interrupt