Termination and thread interruption of java threads, and termination interruption of java threads

Source: Internet
Author: User

Termination and thread interruption of java threads, and termination interruption of java threads

About thread termination:

1. Generally, the thread enters the dead state after execution is completed, and the thread is terminated naturally.

2. Some server programs may be required for business purposes and resident systems. It is an infinite loop used to provide services. So how should we end this thread.

I. Thread termination

In the Thread class, JDK provides us with a stop () method to terminate the Thread. Once this method is called, it will immediately terminate the Thread and immediately release the object lock. If a thread executes half of the business and calls this method, data inconsistency may occur.

Data Consistency: at the same time point, the value of key1 obtained in node A should be the same as that obtained in Node B.

For example, a user student table is maintained in the database. The table contains two pieces of data:

Id = 1 name = "A" id = 2 name = ""

If we use a Student object to save these records, the object will either save the records with id = 1 de or with id = 2. If this Student object saves half of the records with id = 1 and half of the records with id = 2 (that is, id = 1 name = "a"), data consistency problems occur.

See the figure to explain why the stop operation causes data consistency problems:

Each read and write operation requires a live student object lock. Only the thread that obtains the lock has the right to operate on the object. That is to say, the role of the student object lock is to maintain object consistency, if the thread calls the stop method when writing half of the written data, the object will be destroyed and the object lock will be released, another read thread waiting for the lock will obtain the lock, and the data read by the execution operation is obviously incorrect.

Sample Code:

Public class StopTest2 {private static Student student = new Student (); public static void main (String [] args) {new Thread (new Thread_read ()). start (); while (true) {Thread thread_writer = new Thread (new Thread_writer (); thread_writer.start (); try {Thread. sleep (1500);} catch (InterruptedException e) {e. printStackTrace ();} thread_writer.stop () ;}} static class Thread_read implements Runnable {@ Ove Rride public void run () {while (true) {synchronized (student) {// lock the shared resources so that read/write splitting does not affect each other and maintain object consistency. 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 Resource:" + student) ;}} Thread. yield (); // release cup execution permission} static class Thread_writer implements Runnable {@ Override public void run () {while (true) {synchronized (student) {// lock the shared resources so that read/write splitting does not affect each other. Maintain the object consistency int mm = new Random (). nextInt (10); student. setId (mm); try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} student. setName (String. valueOf (mm);} Thread. yield (); // release cup execution permission }}} class Student {private int id = 0; private String name = "0"; public int getId () {return id ;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}@ Override public String 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 ensure correct thread termination: The program determines the thread termination time. Define an identifier to control whether the program is executed by changing the identifier.

Static class Thread_writer implements Runnable {private boolean flag = false; public void setFlag (boolean flag) {this. flag = flag;} @ Override public void run () {while (! Flag) {synchronized (student) {// lock the shared resources so that read/write splitting does not affect each other. maintain the consistency of the object int mm = new Random (). nextInt (10); student. setId (mm); try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} student. setName (String. valueOf (mm);} Thread. yield (); // release the CPU execution right }}}View Code 2. Thread interruption

We found that using stop to terminate a thread would result in a data consistency problem. Therefore, we use the control mark to control the thread termination. Is there a proper method for JDK to terminate a thread? That is, "thread interruption"

Thread interruption means to stop the target thread, but it does not cause the thread to terminate immediately. Instead, it sends a notification to the thread telling the thread jvm that you want to exit the execution. When the target thread exits, it is entirely determined by itself (if it is stopped immediately, it will cause the same problem as the stop ).

Three methods related to thread interruption in JDK:

// Thread interruption public void interrupt () {}// determine whether the thread is interrupted public boolean isInterrupted () {}// determine whether the thread is interrupted, and clear the current interrupt status public static boolean interrupted (){}

1. Will thread interruption occur if thread interruption occurs?

Public class InterruptTest {public static void main (String [] args) {Thread thread = new Thread () {@ Override public void run () {while (true) {System. out. println ("========= true ======") ;}}; thread. start (); try {Thread. sleep (0);} catch (InterruptedException e) {e. printStackTrace ();} thread. interrupt (); // call the thread interruption Method }}View Code

Run the code and find that the thread has not been terminated.

How to terminate a thread

Public class InterruptTest {public static void main (String [] args) {Thread thread = new Thread () {@ Override public void run () {while (true) {if (this. isInterrupted () {// checks whether the current thread is in the interrupted status System. out. println ("========= true ======"); break ;}}}; thread. start (); try {Thread. sleep (0);} catch (InterruptedException e) {e. printStackTrace ();} thread. interrupt (); // call the thread interruption Method }}View Code

The Code shows that this is similar to the final disconnection of the self-controlled thread. But thread interruption is more severe.

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.