"Understanding Java Multi-Thread two" multi-threaded scheduling and daemon process

Source: Internet
Author: User

As mentioned in the previous article, all the threads in the ready state, the operating system chooses the highest priority for scheduling, then is the priority of the thread must be higher than the priority of the thread to execute first? How are threads prioritized? This article, the building is going to say this problem! Welcome to my personal blog homepage www.anycodex.com

1. Priority of Threads
In Java, the thread priority has a range of 0-10, and the larger the integer value, the higher the precedence level.

    • A few related macro definitions:
Max_priority 10, highest priority

Min_priority 1, lowest priority

Norm_priority 5, default priority

    • Related interfaces
setpriority (int x), sets the priority of the thread

GetPriority (), gets the priority of the thread

Since there is a priority between threads, is it necessarily higher priority than a thread with a lower priority? The answer is no. Only high-priority threads have a greater likelihood of getting CPUs, but that does not mean that they will be executed first.

Little friends, let's take a look at an example of a code, the whirring (~ o ~) ~zz

Package net.mindview.util;//first step, implement Runnable interface class Mythreadrunning implements runnable{//second step, overriding the Run method public void        Run () {for (int i = 0; I <= 3; i++) {System.out.println (Thread.CurrentThread (). GetName ()); }}}public class MyThread {public static void main (string[] args) {///third step, instantiating a custom thread class object Mythr        eadrunning mtr1 = new mythreadrunning ();        mythreadrunning mtr2 = new mythreadrunning ();        mythreadrunning MTR3 = new mythreadrunning ();        Fourth, instantiate a thread class object and pass in the custom thread class object as a parameter, followed by the thread name Thread1 = new Thread (MTR1, "Thread 1 is running");        Thread thread2 = new Thread (MTR2, "Thread 2 is Running");                Thread thread3 = new Thread (MTR3, "Thread 3 is Running");        Thread1.setpriority (thread.max_priority);        Thread2.setpriority (thread.min_priority);        Thread3.setpriority (thread.norm_priority);        Fifth step, call the Start method to start the thread Thread1.start ();       Thread2.start (); Thread3.start (); }}
Operation Result:

Thread 1 is running
Thread 1 is running
Thread 2 is running
Thread 1 is running
Thread 3 is running
Thread 3 is running
Thread 3 is running
Thread 3 is running
Thread 1 is running
Thread 2 is running
Thread 2 is running
Thread 2 is running

When do the little friends understand? A thread with a high priority will not necessarily be executed first? It's just that there's a bigger possibility of getting CPU scheduling. My little friends may ask, are they prioritized, or are there no guarantees that the threads will be executed in the order I want them to be? Well, after reading the following, you can learn some of the tricks, it is our thread scheduling.

2. Thread scheduling
On the thread scheduling, we need to understand that only good scheduling, can play a good system performance, improve the execution efficiency of the program. However, no matter how good scheduling, also can not accurately control the operation of the program. Usually we adopt the method of thread scheduling mainly have Sleep,yield and join method. Next we look at ha!

Sleep () method, sleeping is as the English meaning of the release of the night. When a program goes to sleep, it will give the CPU resources to other threads, and when the sleep time, the program automatically from the blocking state into a ready state, waiting for the scheduling of CPU resources. The sleep () parameter is millisecond, such as sleep (1000) is to let the thread hibernate 1s. When calling this method, you need to catch the interruptedexception exception. Look at the code below.

Package net.mindview.util;//first step, implement Runnable interface class Mythreadrunning implements runnable{//second step, overriding the Run method public void            Run () {for (int i = 0; I <= 3; i++) {System.out.println (Thread.CurrentThread (). GetName ());            try {thread.sleep (1000);            } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }}}}public class MyThread {public static void main (string[] args) {//Third step, instantiating a custom        Thread Class object Mythreadrunning mtr1 = new mythreadrunning ();        mythreadrunning mtr2 = new mythreadrunning ();        mythreadrunning MTR3 = new mythreadrunning ();        Fourth, instantiate a thread class object and pass in the custom thread class object as a parameter, followed by the thread name Thread1 = new Thread (MTR1, "Thread 1 is running");        Thread thread2 = new Thread (MTR2, "Thread 2 is Running");                Thread thread3 = new Thread (MTR3, "Thread 3 is Running");      Fifth step, call the Start method to start the thread  Thread1.start ();        Thread2.start ();    Thread3.start (); }}
Operation Result:

Thread 2 is running
Thread 3 is running
Thread 1 is running
Thread 3 is running
Thread 2 is running
Thread 1 is running
Thread 2 is running
Thread 1 is running
Thread 3 is running
Thread 3 is running
Thread 2 is running
Thread 1 is running

As can be seen from the results of the operation, the thread cannot control the order accurately. Each run may have a different result.

    • Yield method
The yield method, like the meaning of English, is a concession. Pauses the current thread, letting the CPU run and entering a ready state, allowing other threads to gain CPU time. However, there is no point in preemptive OS, or no effect.

Package net.mindview.util;//first step, implement Runnable interface class MYTHREADRUNNING1 implements runnable{//second step, overriding run method public Voi        D run () {for (int i = 0; I <= 3; i++) {System.out.println (Thread.CurrentThread (). GetName ());        }}}//first step, implement Runnable interface class MyThreadRunning2 implements runnable{//second step, overriding run method public void run () {            for (int i = 0; I <= 3; i++) {System.out.println (Thread.CurrentThread (). GetName ());        Thread.yield (); }}}public class MyThread {public static void main (string[] args) {///third step, instantiating a custom thread class object Mythre        AdRunning1 mtr1 = new MyThreadRunning1 ();        MyThreadRunning2 mtr2 = new MyThreadRunning2 ();        Fourth, instantiate a thread class object and pass in the custom thread class object as a parameter, followed by the thread name Thread1 = new Thread (MTR1, "Thread 1 is running");                Thread thread2 = new Thread (MTR2, "Thread 2 is Running");        Fifth step, call the Start method to start the thread Thread1.start ();    Thread2.start (); }}
Run Effect: If the possible running result without yield:

Thread 1 is running thread 1 is running
Thread 2 is running thread 2 is running
Thread 1 is running thread 1 is running
Thread 2 is running thread 1 is running
Thread 1 is running thread 1 is running
Thread 2 is running thread 2 is running
Thread 1 is running thread 2 is running
Thread 2 is running thread 2 is running

As you can see from the running effect, thread 2 gives out CPU resources once per execution, but it is only possible to run the results.

    • Join method
The role of the Join method may not be as simple as the English meaning, so the Join method is intended to allow one thread to wait for the other thread to execute before continuing. You can add a parameter, a long-type millisecond, to wait for the process to terminate for a maximum of a number of seconds. If THREAD.MT () is waiting for thread thread to finish executing, then other programs are executed. We can look at the following code:
Package net.mindview.util;//first step, inherit the Thread class Mythreadrunning extends thread{//constructor public mythreadrunning () {    Super ("My Thread"); }//Second step, overriding the Run method public void run () {for (int i = 0; I <= 3; i++) {System.out.println ("Create a new            Thread "+ getName () +i);            try {sleep (1000);            } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }}}}public class MyThread {public static void main (string[] args) {/                        /Step three, instantiate a custom thread class object mythreadrunning mtr = new mythreadrunning ();                  Fourth step, call the Start method to start the Run Method Mtr.start ();        try {mtr.join ();        } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); } System.out.println ("mtr you're done, right? I'm the main thread, I'm going to print it.    "); }}
Operation Result:

Create a new thread my Thread0
Create a new thread my Thread1
Create a new thread my Thread2
Create a new thread my Thread3
MTR, you're done, right? I'm the main thread, I'm going to print it.

3. Daemon Process
Daemons are also called background processes, which are a kind of thread that serves other threads. When the virtual machine detects that no user process is executing, the JVM may exit even if there is a background process.

Related interfaces:

Setdaemon (Boolean) sets a thread as a background process;

Thread.isdaemon () Determines whether a thread is a background process.

We can look at the following code:
Package net.mindview.util;//The first step, inheriting the thread class public class MyThread {public static void main (string[] args) {             Thread T1 = new Mycommon ();             Thread t2 = new Thread (new Mydaemon ());        T2.setdaemon (TRUE);             Set to daemon thread T2.start ();     T1.start ();                     }} class Mycommon extends Thread {public void run () {for (int i = 0; i < 5; i++) { SYSTEM.OUT.PRINTLN ("Thread 1" + i + "time to execute!)                     ");                     try {thread.sleep (7);                     } catch (Interruptedexception e) {e.printstacktrace (); }}}} class Mydaemon implements Runnable {public void run () {for (Long i = 0; I < 9 999999L; i++) {System.out.println ("background line Cheng Di" + i + "times executed!                     ");                     try {thread.sleep (7);           } catch (Interruptedexception e) {                  E.printstacktrace (); }             }     } }
Operation Result:

Thread 1 executes for the NO. 0 time!
The background thread executes for the NO. 0 time!
The background thread executes for the 1th time!
Thread 1 executes for the 1th time!
Thread 1 executes for the 2nd time!
The background thread executes for the 2nd time!
Thread 1 executes for the 3rd time!
The background thread executes for the 3rd time!
Thread 1 executes for the 4th time!
The background thread executes for the 4th time!
The background thread executes for the 5th time!

Students, from the running results can be seen, the background thread has not finished, the program will quit.



The above is our second part of the Java Multi-threading, summed up, this article mainly talk about the Java multi-threading scheduling problem. Scheduling methods mainly sleep ah, concessions ah, and join AH and so on. However, it is clear that no matter how the programmer does the scheduling, the precise control of the thread is not possible. At that time, good thread scheduling can improve the efficiency of program operation. Finally we talk about the daemon thread, which is the background thread, where the virtual machine detects that no user thread is running, and exits regardless of the background thread. Well, that's all there is, little friends, all right? The following article, we want to learn the classic problem, producers and consumers, such as thread synchronization problems, refueling refueling, not to be continued Oh ~ ~ ~

"Understand Java multi-thread two" multi-threaded scheduling and daemon

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.