Java multi-thread Series 8-thread priority, multi-thread 8-

Source: Internet
Author: User

Java multi-thread Series 8-thread priority, multi-thread 8-

Set the thread priority in java to use setPriority. The source code in jdk is as follows:

public final void setPriority(int newPriority) {        ThreadGroup g;        checkAccess();        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {            throw new IllegalArgumentException();        }        if((g = getThreadGroup()) != null) {            if (newPriority > g.getMaxPriority()) {                newPriority = g.getMaxPriority();            }            setPriority0(priority = newPriority);        }    }

In java, the priority of threads is divided into 1 ~ If the 10 levels are less than 1 or greater than 10, an IllegalArgumentException exception is thrown.

Use three constants in JDK to predefine the priority:

  /**     * The minimum priority that a thread can have.     */    public final static int MIN_PRIORITY = 1;    /**     * The default priority that is assigned to a thread.     */    public final static int NORM_PRIORITY = 5;     /**     * The maximum priority that a thread can have.     */    public final static int MAX_PRIORITY = 10;
Inheritance of thread priority

In java, the priority of A thread is inherited. For example, if A thread starts A thread B, the priority of A and B is the same. For example:

public class MyThread1 extends Thread {    @Override    public void run() {        System.out.println("MyThread1 run priority=" + this.getPriority());        MyThread2 thread2 = new MyThread2();        thread2.start();    }}public class MyThread2 extends Thread {    @Override    public void run() {        System.out.println("MyThread2 run priority=" + this.getPriority());    }}public class Run {    public static void main(String[] args) throws InterruptedException {        System.out.println("main thread begin priority="                + Thread.currentThread().getPriority());        System.out.println("main thread end priority="                + Thread.currentThread().getPriority());        MyThread1 thread1 = new MyThread1();        thread1.start();    }}

The running result is as follows:

Main thread begin priority = 5
Main thread end priority = 5
MyThread1 run priority = 5
MyThread2 run priority = 5

Regular priority

Although the setPriority () method can set the thread priority, the effect of setting the priority is not displayed.

Example:

public class MyThread1 extends Thread {    @Override    public void run() {        long beginTime = System.currentTimeMillis();        long addResult = 0;        for (int i = 0; i < 10; i++) {            for (int j = 0; j < 50000; j++) {                Random random = new Random();                random.nextInt();                addResult += j;            }        }        long endTime = System.currentTimeMillis();        System.out.println("* * * * * thread 1 use time=" + (endTime - beginTime));    }}public class MyThread2 extends Thread {    @Override    public void run() {        long beginTime = System.currentTimeMillis();        long addResult = 0;        for (int i = 0; i < 10; i++) {            for (int j = 0; j < 50000; j++) {                Random random = new Random();                random.nextInt();                addResult += j;            }        }        long endTime = System.currentTimeMillis();        System.out.println("* * * * * thread 2 use time=" + (endTime - beginTime));    }}public class Run {    public static void main(String[] args) throws InterruptedException {                for(int i=0;i<5;i++){            MyThread1 thread1=new MyThread1();            thread1.setPriority(10);            thread1.start();            MyThread2 thread2 =new MyThread2();            thread2.setPriority(1);            thread2.start();        }    }}

The running result is as follows:

* *** Thread 1 use time = 174
* *** Thread 1 use time = 221
* *** Thread 1 use time = 224
* *** Thread 2 use time = 360
* *** Thread 1 use time = 202
* *** Thread 2 use time = 185
* *** Thread 1 use time = 169
* *** Thread 2 use time = 466
* *** Thread 2 use time = 425
* *** Thread 2 use time = 98

From the above results, we can see that most threads with a higher priority are executed first, but not all threads are executed first. The execution is not completed because the call is called first. If the priority is changed, the execution is completed first and the call sequence of the Code is irrelevant.

The priority has a certain regularity, and the CPU always tries its best to give the execution resource to the thread with a higher priority.

Random priority

A thread with a higher priority may not be executed every time. For example:

public class MyThread1 extends Thread {    @Override    public void run() {        long beginTime = System.currentTimeMillis();        for (int i = 0; i < 1000; i++) {            Random random = new Random();            random.nextInt();        }        long endTime = System.currentTimeMillis();        System.out.println("* * * * * thread 1 use time="                + (endTime - beginTime));    }}public class MyThread2 extends Thread {    @Override    public void run() {        long beginTime = System.currentTimeMillis();        for (int i = 0; i < 1000; i++) {            Random random = new Random();            random.nextInt();        }        long endTime = System.currentTimeMillis();        System.out.println("* * * * * thread 2 use time="                + (endTime - beginTime));    }}public class Run {    public static void main(String[] args) throws InterruptedException {        for (int i = 0; i < 5; i++) {            MyThread1 thread1 = new MyThread1();            thread1.setPriority(5);            thread1.start();            MyThread2 thread2 = new MyThread2();            thread2.setPriority(6);            thread2.start();        }    }}

The running result is as follows:

* *** Thread 1 use time = 5
* *** Thread 2 use time = 4
* *** Thread 1 use time = 5
* *** Thread 1 use time = 4
* *** Thread 1 use time = 4
* *** Thread 2 use time = 6
* *** Thread 2 use time = 3
* *** Thread 2 use time = 5
* *** Thread 1 use time = 2
* *** Thread 2 use time = 6

The thread priority has nothing to do with the print order. Their relationship is uncertain and random.

Related Articles

Java multi-thread Series 8-thread priority

Java multi-thread Series 7-Stop threads

Java multi-thread Series 6-blocking queue

Java multi-thread Series 5-communication between deadlocks and threads

Java multi-thread Series 4-Thread Pool

Java multi-thread Series 3-Thread Synchronization

Java multi-thread Series 2-thread control

Java multi-thread Series 1-thread implementation and Scheduling

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.