线程优先级不能按预期工作? [英] Thread priority does not work as expected?

查看:129
本文介绍了线程优先级不能按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用线程优先级创建了一个程序,我获得了优先级为1的线程和优先级为10的线程的相同点击次数,这让我感到困惑

i made a program using Thread priority and i got the same number of clicks for both thread with priority 1 and thread with priority 10 , its confusing why i am getting this

class clicker implements Runnable {
    int click = 0;
    Thread t;
    private volatile boolean running = true;
    public clicker(int p) {
        t = new Thread(this);
        t.setPriority(p);
    }
    public void run() {
        while (running) {
            click++;
        }
    }
    public void stop() {
        running = false;
    }
    public void start() {
        t.start();
    }
}

class hilopri {
    public static void main(String args[]) {
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        clicker hi = new clicker(1);
        clicker lo = new clicker(10);
        lo.start();
        hi.start();
        try {
            Thread.sleep(10000);
        } 
        catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }
        lo.stop();
        hi.stop();
        // Wait for child threads to terminate.
        try {
            hi.t.join();
            lo.t.join();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException caught");
        }
        System.out.println("Low-priority thread: " + lo.click);
        System.out.println("High-priority thread: " + hi.click);
    }
}

无论优先级如何,输出几乎相同

the output is almost the same regardless of the priority

Low-priority thread: 322141133
High-priority thread: 477591649


推荐答案

实际上,线程优先级的行为无法保证。更改优先级只是对底层操作系统的提示/建议,可以完全忽略。具有低优先级的线程可以获得比具有高优先级的线程更多的CPU周期。因此,底线 - 不要根据线程优先级编写关键代码。

Actually, the behavior of Thread Priority isn't guaranteed. Changing the priority is just a hint / suggestion to the underlying OS that can be totally ignored. A thread with low priority can get more CPU cycles than a thread with high priority. So, bottom line- don't write critical code based on Thread priority.

这篇关于线程优先级不能按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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