当前位置:网站首页>thread priority

thread priority

2022-07-04 06:29:00 Hao Kai

Thread priority

  • Java A thread scheduler is provided to monitor all threads in the program that enter ready state after startup , The thread scheduler determines which thread should be scheduled to execute according to the priority

  • The priority of a thread is represented by a number , Range from 1~10

    • Thread.MIN_PRIORITY=1
    • Thread.MAX_PRIORITY=10
    • Thread.NORM_PRIORITY=5
  • Use the following methods to obtain and change the priority of threads

    • getPriority()
    • setPriority(int xxx)
  • High priority means grabbing CPU The probability of time slice is high , It doesn't have to be done first , We set priorities , For reference only , Unable to determine the final execution order of threads

package com.example.demo.testthread;

public class TestPriority implements Runnable {
    
    public static void main(String[] args) {
    
        TestPriority testPriority = new TestPriority();
        Thread t1 = new Thread(testPriority, " Threads 1");
        t1.start();
        Thread t2 = new Thread(testPriority, " Threads 2");
        t2.setPriority(Thread.MIN_PRIORITY);
        t2.start();
        Thread t3 = new Thread(testPriority, " Threads 3");
        t3.setPriority(Thread.MAX_PRIORITY);
        t3.start();
        Thread t4 = new Thread(testPriority, " Threads 4");
        t4.setPriority(8);
        t4.start();
        Thread t5 = new Thread(testPriority, " Threads 5");
        t5.setPriority(Thread.NORM_PRIORITY);
        t5.start();
        System.out.println(Thread.currentThread().getName()+" perform , The weight of "+Thread.currentThread().getPriority());
        /*  High priority means grabbing CPU The probability of time slice is high , It doesn't have to be done first , We set priorities , For reference only , Unable to determine the final execution order of threads   Output :  Threads 3 perform , The weight of 10 main perform , The weight of 5  Threads 1 perform , The weight of 5  Threads 4 perform , The weight of 8  Threads 5 perform , The weight of 5  Threads 2 perform , The weight of 1 */
    }

    @Override
    public void run() {
    
        System.out.println(Thread.currentThread().getName()+" perform , The weight of "+Thread.currentThread().getPriority());
    }
}
原网站

版权声明
本文为[Hao Kai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141605534749.html