Detailed Java multithreaded programming thread start, break or terminate operation _java

Source: Internet
Author: User
Tags sleep terminates volatile

Thread Start:
Description of the difference between 1.start () and run ()
start (): Its function is to start a new thread, the new thread will execute the corresponding run () method. Start () cannot be called repeatedly.
Run (): Run (), like a normal member method, can be called repeatedly. Calling run () alone executes run () in the current thread and does not start a new thread!
The following is explained in code.

Class Mythread extends thread{public 
  void Run () {
    ...}} 
;
Mythread mythread = new Mythread ();

Mythread.start () starts a new thread and runs the Run () method in the new thread.
Mythread.run () runs the Run () method directly in the current thread and does not start a new thread running run ().

Example of the difference between 2.start () and run ()
below, a simple example demonstrates the difference between them. The source code is as follows:

Demo.java source
class Mythread extends thread{public
  mythread (String name) {
    super (name);
  }

  public void Run () {
    System.out.println (Thread.CurrentThread (). GetName () + ' is running ');
  } 
;

public class Demo {public 
  static void Main (string[] args) { 
    Thread mythread=new mythread ("Mythread");

    System.out.println (Thread.CurrentThread (). GetName () + "Call Mythread.run ()");
    Mythread.run ();

    System.out.println (Thread.CurrentThread (). GetName () + "Call Mythread.start ()");
    Mythread.start ();
  } 


Run Result:

Main call Mythread.run ()
main are running
main call Mythread.start ()
Mythread is running

Results show:
(1) Thread.CurrentThread (). GetName () is the name used to get the "current thread". The current thread is the thread that is dispatching execution in the CPU.
(2) Mythread.run () is called in main thread main, and the Run () method runs directly on the main thread main.
(3) Mythread.start () starts thread Mythread, the Run () method is invoked when thread mythread is started, and the Run () method is run on thread mythread.

Interrupts and terminations of threads

One, thread Interrupt: Interrupt ()
the effect of interrupt () is to interrupt this thread.
This thread interrupts itself to be allowed, and when other threads call this thread's interrupt () method, the permissions are checked by CheckAccess (). This may throw a SecurityException exception.
If this thread is in a blocking state: The call thread's Wait (), the Waiting (long), or (long, int) will let it enter the standby (blocking) state, or the calling thread's join (), join (long), join (long, int), Sleep ( Long), sleep (long, int) also lets it enter a blocking state. If the thread is blocking the state, its interrupt () method is invoked, and its "break state" is cleared and a Interruptedexception exception is received. For example, a thread enters a blocking state by a wait (), at which point the thread is interrupted by interrupt (), and the call to interrupt () immediately sets the thread's interrupt mark to "true", but as the thread is blocked, the interrupt mark is immediately cleared to "false" , at the same time, a Interruptedexception exception is generated.
If the thread is blocked in a selector selector, it is interrupted by interrupt (), the thread's interrupt token is set to true, and it is immediately returned from the selection operation.
If it does not fall into the previous scenario, its interrupt tag is set to "true" when the thread is disconnected through interrupt ().
Breaking a "terminated thread" does not produce any action.

Second, the thread terminates
the Stop () and Suspend () methods in thread are not recommended for use because of inherent insecurity!
Next, I'll discuss the way threads terminate in "blocking state" and "run state" separately, and then summarize a common approach.
1. Terminate a thread in "blocked state"
Typically, we terminate a thread that is in the blocked state by means of "break".
When a thread enters a blocking state by means of a call to sleep (), a Wait (), join (), or the interrupt () of the calling thread to set the thread's interrupt token to true. Because of the blocking state, the interrupt mark is cleared and a interruptedexception exception is generated. You can terminate the thread by placing the interruptedexception in the appropriate form as follows:

@Override public
Void Run () {a
  try {while
    (true) {
      //Execute task ...
    }
  catch (Interruptedexception ie { 
    //due to a interruptedexception exception, exit while (true) loop, thread terminated!
  }
}

Description: The interrupt () of the calling thread produces interruptedexception interrupts while the thread is in a blocked state while the task is constantly executing in while (true). The interrupted capture is outside of the while (true), which exits the while (true) loop!
Note: The Interruptedexception capture is typically placed outside of the while (true) loop, so that the while (true) loop exits when an exception is generated. Otherwise, the interruptedexception in the while (true) loop body requires additional add-and-exit processing. The form is as follows:

@Override public
Void Run () {while
  (true) {
    try {
      //Execute task ...
    } catch (Interruptedexception IE) {
   
    //interruptedexception within a while (true) loop.
      //When the thread produces a interruptedexception exception, while (true) continues to run! Need to manually exit the break
      ;
    }}


   

Description: The above interruptedexception exception is captured within Whle (true). When a interruptedexception exception is generated, it is still in the while (true) loop outside of the catch processing, and an extra execution of a while (true) is required to exit the while (true) loop body.
2. Terminate a thread in "Running state"
Typically, we terminate a thread in "running state" by means of a "tag". These include break marks and extra tags.
(1) terminate the thread by "interrupt Mark".
The form is as follows:

@Override public
Void Run () {while
  (!isinterrupted ()) {
    //Execute task ...
  }
}

Description: Isinterrupted () is to determine whether the thread's interrupt token is true. When the thread is running and we need to terminate it, the thread's interrupt () method can be invoked, and the thread's interrupt mark is true, that is, isinterrupted () returns True. At this point, the while loop exits.
Note: interrupt () does not terminate the thread that is in the "Running state"! It sets the thread's interrupt token to true.
(2) by adding "additional tags".
The form is as follows:

Private volatile Boolean flag= true;
protected void Stoptask () {
  flag = false;
}

@Override public
Void Run () {while
  (flag) {
    //Execute task ...
  }
}

Description: There is a flag tag in the thread, its default value is true, and we provide stoptask () to set the flag tag. When we need to terminate the thread, the Stoptask () method that invokes the thread lets the thread exit the while loop.
Note: The flag is defined as a volatile type to ensure flag visibility. This thread can see the value of the modified flag after the other thread has modified the flag via Stoptask ().
The general thread is in the "blocking state" and "Run State" termination mode, and the more common termination thread is as follows:

@Override public
Void Run () {
  try {
    //1. isinterrupted () guarantee that the thread will terminate as long as the interrupt mark is true. While
    (!isinterrupted ()) {
      //Perform task ...
    }
  catch (Interruptedexception IE) { 
    //2. The interruptedexception exception guarantees that the thread is terminated when the interruptedexception exception is generated.
  }
}

3. Example of terminating a thread
interrupt () is often used to terminate the "blocking state" thread. Refer to the following example:

Demo1.java Source Class Mythread extends Thread {public mythread (String name) {super (name);
      @Override public void Run () {try {int i=0;
        while (!isinterrupted ()) {thread.sleep (100);//Hibernate 100ms i++; 
      System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") loop" + i); } catch (Interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + 
    ") Catch interruptedexception."); }} public class Demo1 {public static void main (string[] args) {try {Thread T1 = new Mythread ("T1") ; 

      New "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is new.");           T1.start (); 

      Start the thread T1 System.out.println (t1.getname () + "(" +t1.getstate () + ") is started.");
      The main thread sleeps 300ms, and then the main thread sends an "interrupt" instruction to T1.
      Thread.Sleep (300);
      T1.interrupt (); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted. ");
      The main thread sleeps 300ms and then looks at the status of the T1.
      Thread.Sleep (300); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted now.");
    catch (Interruptedexception e) {e.printstacktrace ();

 }
  } 
}

Run Result:

T1 (new) is new.
T1 (RUNNABLE) is started.
T1 (RUNNABLE) loop 1
T1 (RUNNABLE) loop 2
T1 (timed_waiting) is interrupted.
T1 (RUNNABLE) Catch interruptedexception.
T1 (terminated) is interrupted now.

Results show:
(1) The thread T1 is created by the new Mythread ("T1") in main thread main, then the thread T1 is started by T1.start ().
(2) After the T1 is started, it will constantly check its interrupt mark, if the interrupt is marked "false", then hibernate 100ms.
(3) When the T1 is dormant, it switches to the main thread main, and the thread T1 in T1.interrupt () is executed when the main thread runs again. T1 receives the interrupt instruction, the T1 interrupt token is set to "false" and the Interruptedexception exception is thrown. In the T1 run () method, an exception is caught outside the loop body, so the loop is terminated.
We made a small change to the result, moving the code block that captures the interruptedexception exception in the Run () method to the while loop.

Demo2.java Source Class Mythread extends Thread {public mythread (String name) {super (name);
    @Override public void Run () {int i=0; 
        while (!isinterrupted ()) {try {thread.sleep (100);//Hibernate 100ms} catch (Interruptedexception IE) { 
      System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") Catch interruptedexception.");
      } i++; 
    System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") loop" + i); }} public class Demo2 {public static void main (string[] args) {try {Thread T1 = new Mythread ("T1") ; 

      New "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is new.");           T1.start (); 

      Start the thread T1 System.out.println (t1.getname () + "(" +t1.getstate () + ") is started.");
      The main thread sleeps 300ms, and then the main thread sends an "interrupt" instruction to T1.
      Thread.Sleep (300);
      T1.interrupt (); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted.");
      The main thread sleeps 300ms and then looks at the status of the T1.
      Thread.Sleep (300); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted now.");
    catch (Interruptedexception e) {e.printstacktrace ();

 }
  } 
}

Run Result:

T1 (new) is new.
T1 (RUNNABLE) is started.
T1 (RUNNABLE) loop 1
T1 (RUNNABLE) loop 2
T1 (timed_waiting) is interrupted.
T1 (RUNNABLE) Catch interruptedexception.
T1 (RUNNABLE) Loop 3
T1 (RUNNABLE) Loop 4
T1 (RUNNABLE) loop 5
T1 (timed_waiting) is interrupted now.
T1 (RUNNABLE) loop 6
T1 (RUNNABLE) loop 7
T1 (RUNNABLE) Loop 8
T1 (RUNNABLE) Loop 9
...

Results show:
Program into the dead loop!
Why is that? This is because the T1 is interrupted by interrupt () while waiting (blocked), and the interrupt mark [that is isinterrupted () is returned false] and a Interruptedexception exception is thrown [ The exception is caught in the while loop body. Therefore, T1 of course will go into the death cycle.
To solve this problem, we need to do an extra exit while loop when catching an exception. For example, adding a break or return in a mythread catch (interruptedexception) solves the problem.
The following is an example of a thread that terminates the status state through an extra tag:

Demo3.java Source Class Mythread extends Thread {Private volatile boolean flag= true;
  public void Stoptask () {flag = false;
  Public Mythread (String name) {super (name);
        @Override public void Run () {synchronized () {try {int i=0;
          while (flag) {thread.sleep (100);//Hibernate 100ms i++; 
        System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") loop" + i); } catch (Interruptedexception IE) {System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getsta

Te () + ") Catch interruptedexception.");}}} public class Demo3 {public static void main (string[] args) {try {mythread T1 = new Mythread ("T1");//New 

      "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is new.");           T1.start (); 

      Start the thread T1 System.out.println (t1.getname () + "(" +t1.getstate () + ") is started."); Main thread Hibernate 300ms, then main thread toT1 sends an "interrupt" instruction.
      Thread.Sleep (300);
      T1.stoptask ();

      System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted.");
      The main thread sleeps 300ms and then looks at the status of the T1.
      Thread.Sleep (300); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted now.");
    catch (Interruptedexception e) {e.printstacktrace ();

 }
  } 
}

Run Result:

T1 (new) is new.
T1 (RUNNABLE) is started.
T1 (RUNNABLE) loop 1
T1 (RUNNABLE) loop 2
T1 (timed_waiting) is interrupted.
T1 (RUNNABLE) Loop 3
T1 (terminated) is interrupted now.

Related Article

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.