执行此代码时,有时我会注意到具有最低优先级的线程在具有最高优先级的线程之前执行。任何人都可以帮助我理解这里发生了什么?在最大优先级线程之前,最低优先级线程是如何执行的?
class Test implements Runnable
{
public void run()
{
for(int i=0; i<5; i++)
System.out.println(Thread.currentThread().getName());
}
}
class TestMain
{
public static void main(String[] args)
{
Test test = new Test();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setPriority(Thread.MAX_PRIORITY);
t1.setName("Max priority thread");
t2.setPriority(Thread.MIN_PRIORITY);
t2.setName("Min priority thread");
t1.start();
t2.start();
}
}
有时候,我得到的输出作为
Min priority thread
Min priority thread
Min priority thread
Min priority thread
Max priority thread
Max priority thread
Max priority thread
Max priority thread
Max priority thread
Min priority thread
,有时甚至
Max priority thread
Max priority thread
Max priority thread
Max priority thread
Max priority thread
Min priority thread
Min priority thread
Min priority thread
Min priority thread
Min priority thread
从逻辑上讲,最大优先级的线程应该首先启动。但有时候并没有发生。如果这是不可避免的,那么如何确保具有最高优先级的线程始终首先启动?
线程无需根据其优先级执行。最终,它决定何时执行哪个线程的操作系统。你给的优先级只是一个建议。 – TheLostMind
我认为线程优先级只是对底层操作系统的推荐。不能保证哪个线程会首先被执行。 – clamp
@TheLostMind:那么是否有任何方法或算法可以确保首先执行特定的线程? –