`

Java thread priority

    博客分类:
  • JAVA
 
阅读更多

比较好的java书上都写着不要试图用java线程的优先级来确定线程的执行顺序,不过知道下java线程优先级与底层OS之间线程优先级的映射关系也是好的,找了篇文章总结的不错。

转载自:http://www.javamex.com/tutorials/threads/priority_what.shtml

 

What is Java thread priority?

In our introduction to thread priority, we pointed out some problems with the system, notably differences between what priority actually means on different systems. Here, we'll look at how thread priority is actually implemented in Windows and Linux.

Windows priorities

In the Hotspot VM for Windows, setPriority() map to Windows relative priorities (set by the SetThreadPriority() API call). The actual mappings were changed between Java 5 and Java 6 as follows:

Java to Windows priority mappings

 

Java Priority Windows Priority (Java 5) Windows Priority (Java 6)
1 THREAD_PRIORITY_LOWEST
2
3 THREAD_PRIORITY_BELOW_NORMAL
4
5 THREAD_PRIORITY_NORMAL THREAD_PRIORITY_NORMAL
6 THREAD_PRIORITY_ABOVE_NORMAL
7 THREAD_PRIORITY_ABOVE_NORMAL
8 THREAD_PRIORITY_HIGHEST
9 THREAD_PRIORITY_HIGHEST



CPU allocation against thread priority

Figure 1. Approximate CPU allocation against thread priority under Windows XP on a uniprocessor machine. Results for Vista on a dual core machine are very similar.

CPU allocation against thread priority (Linux)

Figure 2. Approximate CPU allocation against thread priority on a uniprocessor machine under Debian Linux (kernel 2.6.18).

In effect, the priority mappings were 'shifted down' to avoid THREAD_PRIORITY_TIME_CRITICAL, apparently following reports that this setting could affect vital processes such as audio. Note that there is really no such mapping to THREAD_PRIORITY_IDLE as suggested by Oaks & Wong (they were possibly misinterpreting a dummy value that appears at the beginning of the priority mapping table in the VM source code).

On Windows, thread priority is a key element in deciding which thread gets scheduled, although the overall priority of a thread is a combination of the process's priority class, the thread's relative priority (values from the table above), plus any temporary "boost" given in specific circumstances (such as on returning from a wait on I/O). But in general:

Lower-priority threads are given CPU when all higher priority threads are waiting (or otherwise unable to run) at that given moment.

The actual proprtion of CPU allotted to a thread therefore depends on how often that situation occurs— there's no relation per se between priority and CPU allocation. Now of course, if this was literally the be-all and end-all to thread scheduling, then there'd quite possibly be lower-priority threads that barely got any CPU at all, being continually starved by higher-priority threads that needed CPU. So Windows has a fallback mechanism, whereby a thread that hasn't run for a long time is given a temporary priority boost. (For more details about some of the points mentioned here, see the section on thread scheduling.)

What this generally means is that on Windows:

Thread priority isn't very meaningful when all threads are competing for CPU.

As an illustration, Figure 1 opposite shows the results of an experiment in which ten threads are run concurrently, one thread with each Java priority. Each thread sits in a CPU-intensive loop (continually a random number using a XORShift generator). Each thread keeps a count of how many numbers it has generated1. After a certain period (60 seconds in this case), all threads are told to stop and queried to find out how many numbers they generated; the number generated is taken as an indication of the CPU time allocated to that thread2. As can be seen, thread priorities 1-8 end up with a practically equal share of the CPU, whilst priorities 9 and 10 get a vastly greater share (though with essentially no difference between 9 and 10). The version tested was Java 6 Update 10. For what it's worth, I repeated the experiment on a dual core machine running Vista, and the shape of the resulting graph is the same. My best guess for the special behaviour of priorities 9 and 10 is that THREAD_PRIORITY_HIGHEST in a foreground window has just enough priority for certain other special treatment by the scheduler to kick in (for example, threads of internal priority 14 and above have their full quantum replenished after a wait, whereas lower priorities have them reduced by 1).

Java thread priority to nice value mappings in Linux Java thread priority Linux nice value
1 4
2 3
3 2
4 1
5 0
6 -1
7 -2
8 -3
9 -4
10 -5

Linux priorities

Under Linux, you have to go through more hoops to get thread priorities to function at all, although in the end, they may be more useful than under Windows. In Linux:

  • thread priorities only work as of Java 6 onwards;
  • for them to work, you must be running as root (or with root privileges via setuid);
  • the JVM parameter -XX:UseThreadPriorities must be included.

The rationale behind requiring root privileges to alter thread priorities largely eludes me. Whether or not Linux itself generally should place such a restriction on changing nice values is arguable, bit since it doesn't, it seems odd to add it to the JVM (as opposed to, say, building in a restriction via the Java SecurityManager). And does anyone really run, say, their web server as root?

Assuming you go through these steps to enable them, Java thread priorities in Hotspot map to nice values. Unlike Windows priorities, Linux nice values are used as a target for CPU allocation (although like Windows, recent versions of Linux— from kernel 2.6.8 onwards— also apply various heuristics to temporarily boost or penalise threads). The mappings from Java priorities to Linux nicevalues are given in the table opposite. Note that:

  • nice value means "how nice the thread is to other threads", so a lower number means higher priority;
  • Java doesn't actually map to the full range (nice values go from -20 to 19), probably to prevent negative impact on system threads.

Figure 2 shows the results of the thread priority experiment repeated under Linux with kernel 2.6.18. The different coloured traces simply represent 3 separate runs of the experiment. The graph shows that there is a correlation between Java priority (nice value) and CPU allocation, although it is far from linear.

Solaris priorities

Sun have published more detailed information on Solaris thread priorities.


1. To reduce the number of memory writes, each thread actually incremented the counter when the bottom 7 bits of the random number generated were all set. However, this should not affect the test, since millions of numbers were generated by each thread, and the bits of numbers generated by XORShift are generally considered equally random.
2. For validation purposes, each thread also recorded its elapsed CPU time as reported by ThreadMXBean. The corresponding graphs have essentially the same shape, but on the machines tested on, the granularity of measurements using the count method is actually better.

分享到:
评论

相关推荐

    Java Thread Programming

    线程的优先级也是Java线程编程中的一个重要概念,Java定义了10个线程优先级,从MIN_PRIORITY(1)到MAX_PRIORITY(10),默认优先级是NORM_PRIORITY(5)。不过,线程调度器可能会根据系统情况调整优先级,因此优先级并不...

    Java_programming_code_improve_thread_priority.rar_java programmi

    在Java中,线程优先级范围从`Thread.MIN_PRIORITY`(通常为1)到`Thread.MAX_PRIORITY`(通常为10),还有一个特殊的优先级`Thread.NORM_PRIORITY`(通常为5),这是默认的线程优先级。较高的优先级意味着线程更有可能被...

    Java Thread Programming (Sams) java线程编程(含code)

    - Java线程有三个内置优先级:`MIN_PRIORITY`, `NORM_PRIORITY`, `MAX_PRIORITY`,但实际效果依赖于操作系统的调度策略。 8. **线程通信** - `BlockingQueue`: 用于线程间数据交换,提供阻塞读写操作,避免忙等待...

    java thread

    每个线程都有一个优先级,范围从`Thread.MIN_PRIORITY`(1)到`Thread.MAX_PRIORITY`(10),默认值为`Thread.NORM_PRIORITY`(5)。但是,优先级高的线程并不保证一定先执行,只是相对有机会先被执行。 线程同步是Java中...

    java Thread

    - Java线程有10个优先级,`Thread.MIN_PRIORITY`(1)到`Thread.MAX_PRIORITY`(10),默认优先级为`Thread.NORM_PRIORITY`(5)。然而,线程优先级并不保证执行顺序,实际调度依赖于操作系统的线程调度策略。 8. ...

    java thread的教程

    ### Java线程教程知识点概述 #### 一、关于本教程 本教程主要介绍Java线程的基础知识,包括线程的概念、为什么线程有用以及如何开始编写简单的多线程程序。此外,还将探讨更复杂的线程应用程序的基本构建块,如...

    java核心编程之javathread

    Java线程(JavaThread)是Java程序中执行的独立单元,它是Java多线程编程的基础。在Java中,每个应用程序至少有一个线程,通常被称为"主线程",用于执行程序的主要逻辑。Java线程允许程序同时执行多个任务,极大地...

    javathread.part02.rar

    `javathread.part02.rar`这个压缩包可能包含的是关于Java线程深入理解和实践的材料,可能是代码示例、课件或教程。 Java线程的创建主要有两种方式:通过实现Runnable接口和继承Thread类。实现Runnable接口更为灵活...

    ThreadPriority.java

    class ThreadDemo extends Thread { public thread1(String s) { super(s);... thread1.setPriority(thread.MIN_PRIORITY); thread1.setPriority(thread.MIN_PRIORITY); thread1.start(); thread2.start(); } }

    Java课件\thread.rar

    - Java中线程有10个优先级,从`Thread.MIN_PRIORITY`(1)到`Thread.MAX_PRIORITY`(10),默认优先级为`Thread.NORM_PRIORITY`(5)。不过,优先级并不能保证线程的执行顺序,仅对相同状态的线程有一定的影响。 6. **...

    javathread.part03.rar

    `javathread.part03.rar`这个压缩包文件很可能包含了关于Java线程深入理解和实践的资源,可能是代码示例、教程文档或者课件。在这个部分,我们将探讨Java线程的一些关键知识点。 1. **线程创建**: Java提供了两种...

    java多线程thread实例

    `Thread`类是Java中的核心类,它允许我们创建并控制独立的执行线程。在这个实例中,我们将深入探讨如何使用`Thread`类创建和管理多线程。 1. **线程的基本概念** - **线程**:线程是程序执行的最小单元,一个进程...

    javaThread正确的示例.rar

    本示例“javaThread正确的示例”旨在展示如何正确地创建和管理Java线程,以提高程序的并发性能。下面将详细介绍相关知识点。 1. **线程的创建方式** - **实现Runnable接口**:这是最常见的创建线程的方式,只需...

    javathread.part01.rar

    - Java线程有10个优先级,从Thread.MIN_PRIORITY(1)到Thread.MAX_PRIORITY(10),默认优先级为Thread.NORM_PRIORITY(5)。但线程调度器可能不会严格遵循优先级。 7. **死锁与活锁** - 死锁:两个或更多线程相互等待...

    java一个多线程的经典例子

    优先级范围为1到10,其中1是最低优先级(`Thread.MIN_PRIORITY`),10是最高优先级(`Thread.MAX_PRIORITY`),默认值为5(`Thread.NORM_PRIORITY`)。虽然设置了线程优先级,但实际运行时是否有效取决于操作系统对线程...

    利用Thread创建线程-java

    Java线程有10个优先级,`Thread.NORM_PRIORITY`(默认优先级)是5,`Thread.MIN_PRIORITY`是1,`Thread.MAX_PRIORITY`是10。但是,线程调度器可能不会严格按照优先级执行,具体取决于操作系统。 5. **守护线程...

    java线程Thread

    Java线程有10个优先级,从Thread.MIN_PRIORITY(1)到Thread.MAX_PRIORITY(10),默认优先级是Thread.NORM_PRIORITY(5)。不过,线程优先级并不保证线程的执行顺序,JVM会根据系统的负载和策略来调度线程。 五、...

    java线程与并行(主要讲解java的nio包某些内容)

    Java线程可以通过继承`java.lang.Thread`类或实现`Runnable`接口来创建。 ##### 创建线程 1. **继承Thread类** - 创建`Thread`类的子类并重写`run()`方法。 - 实例化子类对象,并调用`start()`方法启动线程。 ...

Global site tag (gtag.js) - Google Analytics