Home Java javaTutorial Java thread priority

Java thread priority

Sep 26, 2019 pm 03:37 PM
java

Java thread priority

Java thread priority

In the Thread class, the following attributes are used to represent the priority.

private int priority;
Copy after login

We can set a new priority through setPriority(int newPriority) and get the priority of the thread through getPriority().

Some information draws a conclusion through the following example: the default priority of Java threads is 5.

public static void main(String[] args) {
    Thread thread = new Thread();
    System.out.println(thread.getPriority());
}
// 打印结果:5
Copy after login

In fact, this is completely wrong. I just saw the surface. Look at the example below. We changed the priority of the current thread to 4 and found that the priority of the child thread thread is also 4.

public static void main(String[] args) {
    Thread.currentThread().setPriority(4);
    Thread thread = new Thread();
    System.out.println(thread.getPriority());
}

// 打印结果:4
Copy after login

This is a slap in the face. If the default priority of a thread is 5, the newly created thread thread without setting the priority should be 5, but it is actually 4. Let's take a look at the source code of Thread initialization priority.

Thread parent = currentThread();
this.priority = parent.getPriority();
Copy after login

It turns out that the default priority of a thread is to inherit the priority of the parent thread. In the above example, we set the priority of the parent thread to 4, so the priority of the child thread also becomes 4.

Strictly speaking, the default priority of the child thread is the same as the parent thread, and the default priority of the Java main thread is 5.

There are three priorities defined in Java, namely the lowest priority (1), the normal priority (5), and the highest priority (10). The code is as follows. The Java priority range is [1, 10], setting the priority of other numbers will throw an IllegalArgumentException exception.

/**
 * 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;
Copy after login

Next, let’s talk about the role of thread priority. Let's look at the following code first. The code logic is to create 3000 threads, which are: 1000 threads with priority 1, 1000 threads with priority 5, and 1000 threads with priority 10. Use minTimes to record the sum of the runtime timestamps of 1000 MIN_PRIORITY threads, use normTimes to record the sum of the runtime timestamps of 1000 NORM_PRIORITY threads, and use maxTimes to record the sum of the runtime timestamps of 1000 MAX_PRIORITY threads. By counting the sum of the running timestamps of each priority level, the smaller the value, the higher the priority. Let's run it and see.

public class TestPriority {
    static AtomicLong minTimes = new AtomicLong(0);
    static AtomicLong normTimes = new AtomicLong(0);
    static AtomicLong maxTimes = new AtomicLong(0);

    public static void main(String[] args) {
        List<MyThread> minThreadList = new ArrayList<>();
        List<MyThread> normThreadList = new ArrayList<>();
        List<MyThread> maxThreadList = new ArrayList<>();

        int count = 1000;
        for (int i = 0; i < count; i++) {
            MyThread myThread = new MyThread("min----" + i);
            myThread.setPriority(Thread.MIN_PRIORITY);
            minThreadList.add(myThread);
        }
        for (int i = 0; i < count; i++) {
            MyThread myThread = new MyThread("norm---" + i);
            myThread.setPriority(Thread.NORM_PRIORITY);
            normThreadList.add(myThread);
        }
        for (int i = 0; i < count; i++) {
            MyThread myThread = new MyThread("max----" + i);
            myThread.setPriority(Thread.MAX_PRIORITY);
            maxThreadList.add(myThread);
        }

        for (int i = 0; i < count; i++) {
            maxThreadList.get(i).start();
            normThreadList.get(i).start();
            minThreadList.get(i).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("maxPriority 统计:" + maxTimes.get());
        System.out.println("normPriority 统计:" + normTimes.get());
        System.out.println("minPriority 统计:" + minTimes.get());
        System.out.println("普通优先级与最高优先级相差时间:" + (normTimes.get() - maxTimes.get()) + "ms");
        System.out.println("最低优先级与普通优先级相差时间:" + (minTimes.get() - normTimes.get()) + "ms");

    }

    static class MyThread extends Thread {

        public MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            System.out.println(this.getName() + " priority: " + this.getPriority());
            switch (this.getPriority()) {
                case Thread.MAX_PRIORITY :
                    maxTimes.getAndAdd(System.currentTimeMillis());
                    break;
                case Thread.NORM_PRIORITY :
                    normTimes.getAndAdd(System.currentTimeMillis());
                    break;
                case Thread.MIN_PRIORITY :
                    minTimes.getAndAdd(System.currentTimeMillis());
                    break;
                default:
                    break;
            }
        }
    }
}
Copy after login

The execution results are as follows:

# 第一部分
max----0 priority: 10
norm---0 priority: 5
max----1 priority: 10
max----2 priority: 10
norm---2 priority: 5
min----4 priority: 1
.......
max----899 priority: 10
min----912 priority: 1
min----847 priority: 5
min----883 priority: 1

# 第二部分
maxPriority 统计:1568986695523243
normPriority 统计:1568986695526080
minPriority 统计:1568986695545414
普通优先级与最高优先级相差时间:2837ms
最低优先级与普通优先级相差时间:19334ms
Copy after login

Let’s analyze the results together. Let’s look at the first part first. The threads executed at the beginning have high priority, normal priority, and low priority. The threads executed at the end also have various priorities. This shows that: threads with high priority do not necessarily mean higher priority than threads with higher priority. Threads with lower priority are executed first. You can also put it another way: the order of code execution has nothing to do with the priority of the thread. Looking at the results of the second part, we can find that the sum of the execution timestamps of the 1000 threads with the highest priority is the smallest, while the sum of the execution timestamps of the 1000 threads with the lowest priority is the largest. Therefore, we can know: A batch of high priority Threads will be executed first than a batch of low-priority threads, that is, high-priority threads are more likely to obtain CPU resources than low-priority threads.

Are there really 10 thread levels in each operating system?

As a cross-platform language, Java has 10 levels of threads, but the thread priority values ​​mapped to different operating systems are different. Next, I will teach you how to check the value of thread priority mapping in each operating system in the OpenJDK source code.

Seeing the Thread source code, setting the thread priority finally calls the local method setPriority0();

private native void setPriority0(int newPriority);
Copy after login

Then we find the method JVM_SetThreadPriority corresponding to setPriority0() in the Thread.c code of OpenJDK ;

static JNINativeMethod methods[] = {
    ...
    {"setPriority0",     "(I)V",       (void *)&JVM_SetThreadPriority},
    ...};
Copy after login

We find the corresponding code segment in jvm.cpp based on JVM_SetThreadPriority;

JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
  JVMWrapper("JVM_SetThreadPriority");
  // Ensure that the C++ Thread and OSThread structures aren&#39;t freed before we operate
  MutexLocker ml(Threads_lock);
  oop java_thread = JNIHandles::resolve_non_null(jthread);
  java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
  JavaThread* thr = java_lang_Thread::thread(java_thread);
  if (thr != NULL) {                  // Thread not yet started; priority pushed down when it is
    Thread::set_priority(thr, (ThreadPriority)prio);
  }
JVM_END
Copy after login

Based on the code in step 3, we can find that the key is the code java_lang_Thread::set_Priority() , continue to look for the set_Priority() method in the thread.cpp code;

void Thread::set_priority(Thread* thread, ThreadPriority priority) {
  trace("set priority", thread);
  debug_only(check_for_dangling_thread_pointer(thread);)
  // Can return an error!
  (void)os::set_priority(thread, priority);
}
Copy after login

The above is the detailed content of Java thread priority. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles