Java 线程优先级没有影响 [英] Java Thread priority has no effect

查看:34
本文介绍了Java 线程优先级没有影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于线程优先级的测试.代码来自 Thinking in Java p.809

This is a test about thread priority. The code is from Thinking in Java p.809

import java.util.concurrent.*;

public class SimplePriorities implements Runnable {
    private int countDown = 5;
    private volatile double d; // No optimization
    private int priority;

    public SimplePriorities(int priority) {
        this.priority = priority;
    }

    public String toString() {
        return Thread.currentThread() + ": " + countDown;
    }

    public void run() {
        Thread.currentThread().setPriority(priority);
        while (true) {
            // An expensive, interruptable operation:
            for (int i = 1; i < 10000000; i++) {
                d += (Math.PI + Math.E) / (double) i;
                if (i % 1000 == 0)
                    Thread.yield();
            }
            System.out.println(this);
            if (--countDown == 0)
                return;
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
            exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        exec.shutdown();
    }
}

我想知道为什么我不能得到像这样的常规结果:

I wonder why I can't get a regular result like:

Thread[pool-1-thread-6,10,main]: 5 
Thread[pool-1-thread-6,10,main]: 4 
Thread[pool-1-thread-6,10,main]: 3 
Thread[pool-1-thread-6,10,main]: 2 
Thread[pool-1-thread-6,10,main]: 1 
Thread[pool-1-thread-3,1,main]: 5 
Thread[pool-1-thread-2,1,main]: 5 
Thread[pool-1-thread-1,1,main]: 5 
Thread[pool-1-thread-5,1,main]: 5 
Thread[pool-1-thread-4,1,main]: 5 
...

但随机结果(每次我运行它都会改变):

but a random result (every time I run it changes):

Thread[pool-1-thread-2,1,main]: 5
Thread[pool-1-thread-3,1,main]: 5
Thread[pool-1-thread-4,1,main]: 5
Thread[pool-1-thread-2,1,main]: 4
Thread[pool-1-thread-3,1,main]: 4
Thread[pool-1-thread-1,1,main]: 5
Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-5,1,main]: 5
...

我使用 i3-2350M 2C4T CPU 和 Win 7 64 位 JDK 7.重要吗?

I use i3-2350M 2C4T CPU with Win 7 64 bit JDK 7. Does it matter ?

推荐答案

Java 线程优先级没有影响

Java Thread priority has no effect

线程优先级是高度特定于操作系统的,并且在许多操作系统上通常影响很小.优先级有助于仅对运行队列中的线程进行排序,并且不会以任何主要方式改变线程的运行频率,除非您在每个线程中都使用大量 CPU.

Thread priorities are highly OS specific and on many operating systems often have minimal effect. Priorities help to order the threads that are in the run queue only and will not change how often the threads are run in any major way unless you are doing a ton of CPU in each of the threads.

您的程序看起来使用了大量 CPU,但除非您的内核数少于线程数,否则通过设置线程优先级,您可能看不到输出顺序的任何变化.如果有空闲的 CPU,那么即使是优先级较低的线程也会被调度运行.

Your program looks to use a lot of CPU but unless you have fewer cores than there are threads, you may not see any change in output order by setting your thread priorities. If there is a free CPU then even a lower priority thread will be scheduled to run.

此外,线程永远不会被饿死.在这种情况下,即使是较低优先级的线程也会给予时间经常运行.您应该会看到较高优先级的线程被赋予时间切片以更频繁地运行,但这并不意味着较低优先级的线程会在运行之前等待它们完成.

Also, threads are never starved. Even a lower priority thread will given time to run quite often in such a situation as this. You should see higher priority threads be given time sliced to run more often but it does not mean lower priority threads will wait for them to finish before running themselves.

即使优先级确实有助于为一个线程提供比其他线程更多的 CPU,线程程序也会受到比赛的影响条件有助于为其执行注入大量随机性.然而,您应该看到的是,最大优先级线程比其他线程更有可能更频繁地吐出它的 0 消息.如果您为 println() 添加优先级,那么在多次运行后应该会变得很明显.

Even if priorities do help to give one thread more CPU than the others, threaded programs are subject to race conditions which help inject a large amount of randomness to their execution. What you should see however, is the max priority thread is more likely to spit out its 0 message more often than the rest. If you add the priority to the println(), that should become obvious over a number of runs.

同样重要的是要注意 System.out.println(...)synchronized 方法,它正在写入 IO,这将极大地影响线程的方式交互并且不同的线程相互阻塞.此外,Thread.yield(); 可以是空操作,具体取决于操作系统如何进行线程调度.

It is also important to note that System.out.println(...) is synchronized method that is writing IO which is going to dramatically affect how the threads interact and the different threads are blocking each other. In addition, Thread.yield(); can be a no-op depending on how the OS does its thread scheduling.

但随机结果(每次我运行它都会改变):

but a random result (every time I run it changes):

没错.线程程序的输出很少是完美的".因为根据定义,线程是异步运行的.我们希望输出是随机的,因为我们希望线程彼此独立地并行运行.那就是他们的力量.如果您期望得到一些精确的输出,那么您不应该使用线程.

Right. The output from a threaded program is rarely if ever "perfect" because by definition the threads are running asynchronously. We want the output to be random because we want the threads to be running in parallel independently from each other. That is their power. If you expecting some precise output then you should not be using threads.

这篇关于Java 线程优先级没有影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆