java thread implementation, thread suspension and termination, thread union join, the basic information to get and set the thread, the thread priority

Address reprint: Speed School  https://www.sxt.cn/Java_jQuery_in_action/eleven-inheritthread.html

1.  multi-threaded through inheritance Thread class

Thread class inherits steps to achieve multi-threading:

      1. responsible for implementing multithreading capabilities in Java class is java.lang.Thread class.

      2. You can create a new thread by creating an instance of Thread.

      3. The method of each thread is run by a specific Thread object corresponds () to complete its operation, the method run () called threads thereof.

      4. to start a thread by calling the start () method of the Thread class.

Multi-threaded through inheritance Thread class

public  class TestThread the extends Thread { // custom class inherits from Thread class
     // RUN () method in the thread body is 
    public  void RUN () {
         for ( int I = 0; I <10; I ++ ) { 
            System.out.println ( the this .getName () + ":" + I); // getName () method returns the name of the thread 
        } 
    } 
 
    public  static  void main (String [] args) { 
        TestThread thread1 = new new TestThread (); // Create a thread objects 
        thread1 .start (); // start the thread
        TestThread thread2 = new TestThread();
        thread2.start();
    }
}

The disadvantage of this way: If our class has inherited a class (such as applet must inherit from the Applet class), you can no longer inherit the Thread class.

2 multi-threaded through the Runnable interface

In the development, the more we realize the application is multi-threaded through the Runnable interface. In this way overcome the shortcomings of the above classes implement threads, which can also inherit a class at the same time implement Runnable. So implement Runnable to be some of the common.

public  class TestThread2 the implements Runnable { // custom class that implements Runnable interface;
     // RUN () method is in thread body; 
    public  void RUN () {
         for ( int I = 0; I <10; I ++ ) { 
            the System.out. the println (Thread.currentThread () getName (). + ":" + I); 
        } 
    } 
    public  static  void main (String [] args) {
         // create a thread object, the implements Runnable interface object as a parameter; 
        = Thread1 the Thread new new the Thread ( new new TestThread2 ()); 
        thread1.start (); //启动线程;
        Thread thread2 = new Thread(new TestThread2());
        thread2.start();
    }
}

Thread State

 

 

 

A thread object in its life cycle, we need to go through five states.

▪ newborn state (New)

      After the establishment of a thread object using the new keyword, the thread object is in a nascent state. Thread nascent state has its own memory space, enter the ready state by calling the start method.

▪ ready state (Runnable)

      Thread in the ready state already has a running condition, but has not yet been assigned to the CPU, in a "thread ready queue" and wait for the system to assign CPU. Execution state is not ready state when the system has selected a Thread object to wait for execution, it will enter the execution state. Once the CPU, thread enters running state and automatically call their own run method. There are 4 reasons why the thread into the ready state:

      1. Create a new thread: Call start () method, enter the ready state;

      2. Stuck Thread: unblocking, enter the ready state;

      3. Run the thread: call yield () method, directly into the ready state;

      4. Run the thread: JVM is switched from the CPU resources to other threads of the present thread.

▪ running state (Running)

      Threads executing code in the operating state of their own run method, until the call is terminated or otherwise blocked or waiting for a resource to complete the task and death. If you do not end execution within a given time slice, it will be down for the system to return to the ready state. Also may be due to certain "events leading to obstruction" into the blocked state.

▪ blocked (Blocked)

      Blocking refers to suspend a thread of execution to wait for a certain condition occurs (such as a resource ready). There are four reasons why blocking:

      1. Perform sleep (int millsecond) method, the current thread to sleep, enter the blocked state. When the specified time to the post, the thread into the ready state.

      2. Perform wait () method, the current thread into the blocked state. When using nofity () method wake up this thread, it enters the ready state.

      3. Thread the runtime, an operation to enter the blocked state (method read () / write () method itself is blocked), such as the implementation of IO stream operations. Only when the cause of the obstruction disappeared operation, the thread into the ready state.

      4. join () thread joint: When the end of a thread wait for another thread to perform, when to proceed, using the join () method.

▪ death state (Terminated)

      Death thread state is the final phase in the life cycle. There are two reasons threads of death. A running thread is completed its run () method within the entire work; the other thread is forcibly terminated as a thread to terminate by executing stop () or destroy () method (Note: stop () / destroy ( ) method has been abandoned JDK, not recommended).

      When a thread enters a state of death, you can not return to the other state.

A typical way to terminate a thread

We generally do not terminate the thread using stop JDK provides () / destroy () method (which itself has been abandoned JDK). The usual practice is to provide a boolean variable type of termination, when this variable is set to false, the running thread is terminated

public  class TestThreadCiycle the implements the Runnable { 
    String name; 
    Boolean Live = to true ; // flag variable indicating whether the thread may be suspended; 
    public TestThreadCiycle (String name) {
         Super ();
         the this .name = name; 
    } 
    public  void RUN () {
         int 0 = I ;
         // when live value is true, continuing the thread body; the end of the cycle to false, and then terminates the thread body; 
        the while (live) { 
            System.out.println (name + (I ++ )); 
        } 
    } 
    public  voidTerminate () { 
        Live = to false ; 
    } 
 
    public  static  void main (String [] args) { 
        TestThreadCiycle TTC = new new TestThreadCiycle ( "Thread A:" ); 
        the Thread T1 = new new the Thread (TTC); // nascent state 
        t1.start ( ); // ready 
        for ( int I = 0; I <100; I ++ ) { 
            System.out.println ( "main thread" + I); 
        } 
        ttc.terminate (); 
        System.out.println ( "STOP TTC ! "  );
    }
}

Suspend thread execution sleep / yield

 Suspend thread execution methods are commonly used sleep () and yield () method, the difference between these two methods are:

      1. sleep () method: You can make a running thread into the blocked state until the sleep time is full, the ready state.

      2. yield () method: You can make a running thread directly into the ready state, so that the right to use the CPU.

Pause thread method -sleep ()

public class TestThreadState {
    public static void main(String[] args) {
        StateThread thread1 = new StateThread();
        thread1.start();
        StateThread thread2 = new StateThread();
        thread2.start();
    }
}
//使用继承方式实现多线程
class StateThread extends Thread {
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(this.getName() + ":" +I);
             the try { 
                the Thread.sleep ( 2000); // call sleep thread () method; 
            } the catch (InterruptedException E) { 
                e.printStackTrace (); 
            } 
        } 
    } 
}

Execution result shown in FIG. (Note: The following illustrates only partial results, can feel a delay before the output result of each run is Thread.sleep (2000) in play statement):

Pause thread method -yield ()

public class TestThreadState {
    public static void main(String[] args) {
        StateThread thread1 = new StateThread();
        thread1.start();
        StateThread thread2 = new StateThread();
        thread2.start();
    }
}
//使用继承方式实现多线程
class StateThread extends Thread {
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(this.getName() + ":" +I); 
            to Thread.yield (); // call to the thread yield () method; 
        } 
    } 
}

Execution result shown in FIG. (Note: The following illustrates only partial results, can cause a thread switch, but without significant delay runtime):

 

 Joint join the thread ()

A thread during the run, you can call the thread B join () method, thread to thread A and B joint. In this way, the thread A must wait after executing thread B is finished, you can proceed. As in the following example, "Daddy thread" to smoke, so united "Son thread" to buy cigarettes, must wait for the "Son thread" cigarettes is completed, "Dad thread" in order to continue to smoke.

public  class TestThreadState {
     public  static  void main (String [] args) { 
        System.out.println ( "father and son cigarettes Story" ); 
        the Thread Father = new new the Thread ( new new FatherThread ()); 
        father.start (); 
    } 
} 
 
class FatherThread the implements Runnable {
     public  void RUN () { 
        System.out.println ( "Daddy want to smoke, found cigarette smoked" ); 
        System.out.println ( "father let his son buy a package GongDaShan" ); 
        the Thread son = new new the Thread (new new SonThread ()); 
        son.start (); 
        System.out.println ( "Father Son et cigarettes back" );
         the try { 
            son.join (); 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
            the System .out.println ( "Dad went out to look for his son where to run" );
             // end JVM. If it is 0 indicates a normal end; if non-zero indicates an abnormal end 
            System.exit (1 ); 
        } 
        System.out.println ( "father happy to take over the smoke began to smoke, and the change to the Son" ); 
    } 
} 
 
class SonThread the implements the Runnable {
     public  voidRUN () { 
        System.out.println ( "son out to buy cigarettes" ); 
        System.out.println ( "son cigarettes 10 minutes" );
         the try {
             for ( int I =. 1; I <= 10; I ++ ) { 
                System.out.println ( "first" + i + "min" ); 
                the Thread.sleep ( 1000 ); 
            } 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
        } 
        System.out.println ( "Buy sons smoke back " ); 
    } 
}

The results shown in Figure:

 

 

Thread method to obtain basic information

 

 

A common method thread

public  class TestThread {
     public  static  void main (String [] argc) throws Exception { 
        the Runnable R & lt = new new the MyThread (); 
        the Thread T = new new the Thread (R & lt, "the Name Test"); // custom thread object, and pass parameters; 
        t.start (); // start the thread; 
        System.out.println ( "IS name:" + t.getName ()); // output thread name; 
        . Thread.currentThread () SLEEP (5000); // thread pause 5 minutes; 
        System.out.println (t.isAlive ()); // determine thread is still running it? 
        System.out.println ( "over!" ); 
    }
}
class MyThread implements Runnable {
    //线程体;
    public void run() {
        for (int i = 0; i < 10; i++)
            System.out.println(i);
    }
}

Results of the:

 

Thread priority 

 1. thread in the ready state, will enter the "ready queue" wait for JVM to pick.

      2. Thread priorities a number in the range from 1 to 10, a thread default priority is five.

      3. Use the following method to obtain or priority thread object.

         int getPriority();

         void setPriority(int newPriority);

Note: Low priority scheduling simply means that the probability of obtaining low. Call a low-priority thread after the first call is not absolute high priority thread.

Two common methods thread

public class TestThread {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyThread(), "t1");
        Thread t2 = new Thread(new MyThread(), "t2");
        t1.setPriority(1);
        t2.setPriority(10);
        t1.start();
        t2.start();
    }
}
class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}

Results of the:

 

Guess you like

Origin www.cnblogs.com/zhzhlong/p/11433712.html