编程语言
首页 > 编程语言> > java-线程优先级程序输出不一致

java-线程优先级程序输出不一致

作者:互联网

下面的程序应该表明具有较高优先级的线程将占用更多的CPU时间.该代码与Herbert Schildt(印度版)在《完全参考:Java(第七版)》中写的代码非常相似-页码237& 238.

class clicker implements Runnable
{
    long click=0;
    Thread t;
    private volatile boolean running=true;

    public clicker(int p)
    {
        t=new Thread(this,"yo yo");
        t.setPriority(p);
    }

    public void run()
    {
        while(running)
            {click++;}
    }
    public void stop()
    {
        running = false;
    }

    public void start()
    {
        t.start();
    }
}
public class ThreadPriorities {

    public static void main(String[] args) {
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        clicker hi=new clicker(Thread.NORM_PRIORITY+2);
        clicker lo=new clicker(Thread.NORM_PRIORITY-2);

        lo.start();
        hi.start();

        try{Thread.sleep(10000);}catch(Exception e){}       

        lo.stop();
        hi.stop();
        try{
            hi.t.join();
            lo.t.join();
        }catch(Exception e){}

        System.out.println("Low priority thread : "+lo.click);
        System.out.println("High priority thread : "+hi.click);
        System.out.println(lo.click<hi.click?true:false);
    }

}

一个输出:

低优先级线程:708527884;
高优先级线程:697458303;

另一个输出:

低优先级线程:676775494;
高优先级线程:687116831;
真正

这可能是什么原因?我有一台配备4GB RAM的Macbook Air.也许这可能是相关的?请告诉我这些输出不一致的原因.提前致谢.

解决方法:

您的两个线程不会互相竞争,因此它们的优先级无关紧要.另一方面,在创建高优先级线程时,低优先级线程正在运行,因此它可能会运行更长的时间.

the thread having higher priority will take up more of the CPU’s time

更高的优先级会使事情运行得更快或运行更多,这是一个普遍的误解.这两个线程不会互相竞争,因此,如果两个线程竞争就获胜就没有区别.优先权并不能使事情进展得更快,而只是在他们觉得重要的情况下给予他们优先权.

输出不一致的原因很可能是一个线程在另一个线程不在时运行的时间高度依赖于系统当时在做什么.

标签:thread-priority,multithreading,java
来源: https://codeday.me/bug/20191111/2018292.html