Java-multi-thread explanation (2)

Source: Internet
Author: User

3. thread status

There are multiple states in the thread, including new status, available status, running status, waiting/blocked/sleeping/monitoring/suspended status, and dead status 5.

1) New status

The new State refers to the state in which the start method is not called after the thread is instantiated. It is not in the ready-to-run state, not an execution thread.

2) running status

After the start () method is started, the thread enters the running state from the new state. The running status is the ready, running, but not running status.

Not only can the stat () method enter the running status, but also can enter the running status from the waiting/blocked/sleep/monitoring/suspension status. For example, after the sleep () method is called, all threads that call yield (after the 0 method is called) enter the runable state.

The running status can also be said to be the status of the thread selected by the CPU. All threads, regardless of the primary and standby threads, may be selected by the CPU to run as long as they are in a running state. Of course, this thread may be in a running state, but it will not run for a long time, this is a special case. In other cases, a thread is always running. For example, if the yield () method is called in a thread, the thread is still running.

3) running status

It is the status of the current execution thread. It can be transferred to the running and waiting/blocked/insomnia/monitoring/suspended status, but can only enter the running status from the running status.

 4) waiting/blocked/sleeping/monitoring/suspended

The waiting/blocked/sleep/monitoring/pending status is complex. It is a collection of many states, but it plays an intermediate role from the running status to the running status. A running thread cannot continue to run for some reason, such as calling the sleep () method or calling the join () method, this thread enters the waiting/blocked/sleep/monitoring/suspended status from the running status. When the sleep () method ends or the thread that calls the join () method ends, the thread becomes runable again.

In addition to the sleep (), yield (), and join () methods, suspend () methods can be used to enter the waiting/blocked/sleep/monitoring/pending status, it means that one thread suspends another thread.

5) dead state

After the run () method in the thread is complete, the thread enters the dead state. An exception occurs when you use the START () method for a thread in the dead state.

4. Thread Scheduling

A thread scheduler is a part of the JVM. It determines which thread should be run at any specified time, And the thread will bring out the running status. Thread Scheduling defines how to exchange tasks in the Java Runtime Environment and how to select the next task to be executed. Thread Scheduling is completed by the priority, sleep (), yield (), and join () methods. As mentioned earlier, the CPU is not sure about the thread selection. Therefore, the scheduling knowledge is used to allow the thread to run in a certain way, rather than completely stipulate it.

1) Priority

Used to determine when a thread is allowed to run. Theoretically, threads with higher priority obtain more CPU time than threads with lower priority. In fact, the CPU length obtained depends on many factors and cannot be determined by priority alone. The priority of the design thread is set using the setpriority (INT level) method. In the level value, min_priority is used to represent the minimum Priority 1; max_priority is used to represent the maximum priority 10; the default priority of a thread is 5, that is, norm_priority.

The method for obtaining the priority of the current thread is getpriority (), which is generally in the form of getpriority ().

Let's look at the program with the following application priority. It shows the priority level through the execution loop and the number of records:

 

Public class test {public static void main (string [] Str) {thread. currentthread (). setpriority (thread. max_priority); mythread T1 = newmythread (thread. norm_priority + 2); mythread t2 = newmythread (thread. norm_priority-2); t1.start (); t2.start (); try {thread. sleep (1000);} catch (exception e) {} t1.stop (); t2.stop (); try {t1.t. join (); t2.t. join ();} catch (exception e) {} system. out. println ("low-priority thread" + t2.click); system. out. println ("high-priority thread" + t1.click) ;}} class mythread implementsrunnable {int click = 0; thread t; private volatile Boolean running = true; Public mythread (int p) {T = new thread (this); T. setpriority (p) ;}@ override public void run () {While (running) {Click ++ ;}} public void stop () {running = false ;} public void start () {T. start ();}}

 

 

The output result of this program is related to the CPU. Running this program also shows the CPU speed.

 2) sleep

Thread sleep () is a static method that forces the thread to enter sleep state. It is necessary to use the sleep () method in a thread to pause the thread. The sleep () method may throw an interruptedexception exception. You must handle the exception when using the sleep () method.

 

Public class test {public static void main (string [] Str) {mythread1 T1 = new mythread1 (); mythread2 t2 = new mythread2 (); mythread3 T3 = new mythread3 (); t1.start (); t2.start (); t3.start () ;}} class mythread1 extendsthread {@ override public void run () {for (INT I = 0; I <20; I ++) {system. out. print ("●"); try {thread. sleep (1000);} catch (exception e) {system. err. println ("exception:" + E) ;}}} class mythread2 extendsthread {@ override public void run () {for (INT I = 0; I <20; I ++) {system. out. print ("■"); try {thread. sleep (1000);} catch (exception e) {system. err. println ("exception:" + E) ;}}} class mythread3 extendsthread {@ override public void run () {for (INT I = 0; I <20; I ++) {system. out. print ("▲"); try {thread. sleep (1000);} catch (exception e) {system. err. println ("exception:" + E );}}}}

 

 

We can see that the running results are still not completely determined. The sleep () method only gives every thread a chance to run.

3) join method

The join () method enables a thread 1 to run after the currently running thread 2. When thread 1 finishes running, it continues to run thread 2. Let's take an example:

 

Public class test {public static void main (string [] Str) {mythread1 T1 = new mythread1 (); mythread2 t2 = new mythread2 (); mythread3 T3 = new mythread3 (); t2.mt1 = T1; t1.start (); t2.start (); t3.start () ;}} class mythread1 extendsthread {@ override public void run () {for (INT I = 0; I <20; I ++) {system. out. println ("●"); try {thread. sleep (5000);} catch (exception e) {system. err. println ("exception:" + E) ;}}} class mythread2 extendsthread {public mythread1 MT1; @ override public void run () {for (INT I = 0; I <20; I ++) {system. out. println ("■"); try {thread. sleep (5000);} catch (exception e) {system. err. println ("exception:" + E) ;}if (I = 10) {try {mt1.join () ;}catch (exception e) {system. err. println ("exception:" + E) ;}}} class mythread3 extendsthread {@ override public void run () {for (INT I = 0; I <20; I ++) {system. out. println ("▲"); try {thread. sleep (5000);} catch (exception e) {system. err. println ("exception:" + E );}}}}

 

 

The running result is as follows:

●▲■ ●■ ▲●■ ●■ ■ ●●●▲■ ▲●■ ●■ ▲ ●■ ●▲●■ ● (I = 10) ▲●●▲●▲●●▲●●●●●▲●▲■ ■ successful build (total time: 29 seconds)

After I = 10, we can see that only the triangle and the solid circle are printed, that is, thread T1 and T3. After T1 is run, we can see that it is quite reassuring, that is, T2.

 4) yield concession Method

The yield () method returns the currently running thread to the runable state. the status issue is described in section 5. The yield () method is used to give threads with the same priority a running opportunity. The yield () method is usually called a concession method, but it often fails to achieve the goal of concession, because it only allows the current thread to return to the runnable state, it is very likely that the running thread will be the same. The following example uses the default priority to explain the yield () method:

 

public class test{    public static void main(String[] str) {        MyThread1 t1 = new MyThread1();        MyThread2 t2 = new MyThread2();        MyThread3 t3 = new MyThread3();        t1.start();        t2.start();        t3.start();    }} class MyThread1 extendsThread{    @Override    public void run() {        for (int i = 0; i < 20; i++) {            System.out.print("●");            Thread.yield();        }    }} class MyThread2 extendsThread{    @Override    public void run() {        for (int i = 0; i < 20; i++) {            System.out.print("■");            Thread.yield();        }    }} class MyThread3 extendsThread{    @Override    public void run() {        for (int i = 0; i < 20; i++) {            System.out.print("▲");        }    }}

 

 

Run the yield () method on T1 and T2. The execution result is printed with a series of triangles, that is, T3. But the concession was not completely successful, and there were still squares and circles in the triangle:

■ ●▲▲▲▲▲●■ ●▲■ ▲▲▲▲▲▲▲▲▲●■ ■ ●■ ●● ■ ●●● ■ ● ●●■ ●■ ■ Successful build (total time: 0 s)

 

 

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.