Termination and thread interruption of Java threads

Source: Internet
Author: User
Tags thread stop

About thread Termination:

1, generally speaking, after the execution of the thread will enter the death state, then the thread naturally terminated.

2, some service-side procedures, may be in business needs, resident system. It is an infinite loop in itself to provide services. So how do we end it for this thread?

one, the termination of the thread

In the thread class, the JDK provides us with a way to terminate the thread stop (); Once called, the method terminates the thread immediately and releases the object lock immediately. If a thread executes half of the business and calls the method, the data inconsistency problem may arise.

Data consistency: At the same point in time, the value you get to Key1 in Node A is the same as the value you get to Key1 in Node B.

For example: The database maintains a user student table with two data:

ID=1 name="Large a" id=2 name="Small A"

If we use a Student object to hold these records, the object either saves the Id=1 de record or saves the id=2 record. If half of the student object is saved in half of the Id=1 records (that is, id=1 name= "small A"), data consistency is a problem.

Look at the diagram to illustrate why stop has data consistency issues:

Read and write operations to live the student object lock, only the thread that obtains the lock has the right to manipulate the object, that is to say, student object lock is to maintain the consistency of the object, if the thread writes to the data in half, call the Stop method, The object will be destroyed and the object lock will be freed, and another read thread waiting for the lock will get the lock, and the data read by the operation is obviously wrong.

code example:

 Public classStopTest2 {Private StaticStudent student=NewStudent ();  Public Static voidMain (string[] args) {NewThread (NewThread_read ()). Start ();  while(true) {Thread thread_writer=NewThread (NewThread_writer ());            Thread_writer.start (); Try{Thread.Sleep (1500); } Catch(interruptedexception e) {e.printstacktrace ();        } thread_writer.stop (); }    }    Static classThread_readImplementsrunnable{@Override Public voidrun () { while(true){                synchronized(student) {//Lock the shared resources so that the read and write separation does not affect each other, maintaining the consistency of the objects                    Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); }                    if(Student.getid ()! =Integer.parseint (Student.getname ())) {System.out.println ("Error resource:" +student); }Else{System.out.println ("Correct resources:" +student); }} Thread.yield ();//Release Cup execution right            }        }    }     Static classThread_writerImplementsrunnable{@Override Public voidrun () { while(true){                synchronized(student) {//Lock the shared resources so that the read and write separation does not affect each other, maintaining the consistency of the objects                    intmm=NewRandom (). Nextint (10);                    Student.setid (mm); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace ();                } student.setname (String.valueof (mm)); } Thread.yield ();//Release Cup execution right            }        }    } }classstudent{Private intId=0; PrivateString 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"Student [id=" + ID + ", name=" + name + "]"; }}
View Code

Execution Result:

Error resource: Student [id=5, name=8] Error resource: Student [ID=4, name=8] Error resource: Student [ID=2, name=5]

How to get the correct terminating thread : The program determines the end time of the thread itself. Defines an identity that controls whether the program executes by changing the identity.

    Static classThread_writerImplementsrunnable{Private Booleanflag=false;  Public voidSetflag (Booleanflag) {             This. flag=Flag; } @Override Public voidrun () { while(!flag) {                synchronized(student) {//Lock the shared resources so that the read and write separation does not affect each other, maintaining the consistency of the objects                    intmm=NewRandom (). Nextint (10);                    Student.setid (mm); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace ();                } student.setname (String.valueof (mm)); } Thread.yield ();//Release Cup execution right            }        }    }
View Codesecond, the interruption of the thread

In the above we find that using the stop termination thread is a data consistency issue, so we control the termination of the thread by controlling the identity, and does the JDK have a proper way to terminate the thread? That would be "thread break."

A thread break is a target thread that stops execution, but it does not cause the thread to terminate immediately, but instead sends a notification to the thread that the JVM wants you to exit execution, and when the target thread exits, it is up to it to decide (if it stops immediately, it will cause the same problem as stop).

Three methods associated with thread break in the JDK:

      public void Interrupt () {}//determine if thread breaks public  Boolean isinterrupted () {} // determines whether the thread is interrupted and clears the current interrupt state  Public Static boolean interrupted () {}

1. Will the thread be interrupted by using thread interrupts?

 Public classInterrupttest { Public Static voidMain (string[] args) {thread thread=NewThread () {@Override Public voidrun () { while(true) {System.out.println ("========true======");        }            }        };        Thread.Start (); Try{Thread.Sleep (0); } Catch(interruptedexception e) {e.printstacktrace (); } thread.interrupt ();//calling thread Break method    }}
View Code

Running the code found that the thread did not terminate.

How to terminate a thread

 Public classInterrupttest { Public Static voidMain (string[] args) {thread thread=NewThread () {@Override Public voidrun () { while(true){                    if( This. isinterrupted ()) {//determine if the current thread is in a broken stateSystem.out.println ("========true======");  Break;        }                }            }        };        Thread.Start (); Try{Thread.Sleep (0); } Catch(interruptedexception e) {e.printstacktrace (); } thread.interrupt ();//calling thread Break method    }}
View Code

Look at the code to see that this is similar to the final break of our own thread control. But the way the thread breaks is even worse.

End of Java thread and thread break

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.