Terminating a thread

Source: Internet
Author: User

The thread class has a method stop. has been disabled when you use Stop (), the program forces the process to break and immediately exits, then the lock is immediately released, this time there will be read and write chaos as follows program

 PackageCom.longfor.dragonshard.service.cost.standard.impl; Public classStopthreadunsafe { Public StaticUser User =NewUser ();  Public Static classuser{Private intID; PrivateString name;  PublicUser () {ID=0; Name= "0"; }         Public intgetId () {returnID; }         Public voidSetId (intID) { This. ID =ID; }         PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; } @Override PublicString toString () {return"user{" + "id=" + ID + ", name= '" + name + ' \ ' + '} '; }    }     Public Static classChangeobjectthreadextendsthread{Private volatile BooleanSTOPME =false;  Public voidStopme () {STOPME=true; } @Override Public voidrun () { while(true){                if(stopme==true){                     Break; }                synchronized(user) {intU = (int) (System.currenttimemillis ()/1000);                    User.setid (U); Try{Thread.Sleep (100); }Catch(Exception e) {e.printstacktrace ();                } user.setname (String.valueof (U));            } Thread.yield (); }        }    }     Public Static classReadobjectthreadextendsthread{@Override Public voidrun () { while(true){                synchronized(user) {if(User.getid ()! =Integer.parseint (User.getname ()))                    {System.out.println (user.tostring ());            }} Thread.yield (); }        }    }     Public Static voidMain (string[] args)throwsexception{NewReadobjectthread (). Start ();  while(true) {Changeobjectthread thread=NewChangeobjectthread ();            Thread.Start (); Thread.Sleep (100);        Thread.stop (); }    }}
View Code

So we set the interrupt condition ourselves instead of using stop Java to set the interrupt condition ourselves

Interrupt () Set interrupt status

Isinterrupt () determine if the interrupt

Interrupted () Determine if the interrupt state is interrupted and cleared

Setting the interrupt state is actually sending a notification to the program that someone wants you to end the process then the operation is entirely under the control of the program if the program exits immediately then it is equivalent to stop so we have to add interrupt processing code

If we do not increase the interrupt code just increase the interrupt state then the program is controlled by the program itself, not us.

 PackageCom.longfor.dragonshard.service.cost.standard.impl; Public classInterrupt { Public Static voidMain (string[] args)throwsinterruptedexception{MyThread Thread=NewMyThread ();        Thread.Start (); Thread.Sleep (1000);    Thread.Interrupt (); }     Public Static classMyThreadextendsthread{@Override Public voidrun () { while(true){                if(Thread.CurrentThread (). isinterrupted ()) {System.out.println ("This thread is interrupted.");  Break;            } Thread.yield (); }        }    }}
View Code

When we use sleep, the program throws an interrupt, so we capture it, and once we catch it, the interrupt state clears, so we're adding the interrupt state.

 PackageCom.longfor.dragonshard.service.cost.standard.impl; Public classSleepinterrupt { Public Static voidMain (string[] args) {MyThread MyThread=NewMyThread ();        Mythread.start ();    Mythread.interrupt (); }     Public Static classMyThreadextendsthread{@Override Public voidrun () { while(true){                if(Thread.CurrentThread (). isinterrupted ()) {System.out.println ("This thread is interrupted ...");  Break; }                Try{Thread.Sleep (2000); }Catch(interruptedexception e) {System.out.println (E.getmessage ());                Thread.interrupted ();            } Thread.yield (); }        }    }}
View Code

Terminating a thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.