Home  >  Article  >  Java  >  Java thread priority

Java thread priority

(*-*)浩
(*-*)浩forward
2019-09-26 15:37:212811browse

Java thread priority

Java thread priority

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

private int priority;

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

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

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();

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;

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;
            }
        }
    }
}

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

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);

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},
    ...};

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

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);
}

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

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete