【发布时间】:2017-12-03 10:31:24
【问题描述】:
我的代码和输出如下:-
我的问题是主线程和线程 t4 的优先级是 9 而线程 t 的优先级是 5 那么为什么第 1 到 4 行(在输出中标记)在第 5 行之前出现,即为什么 t.start() 优先于t4.start() 将由优先级为 9 的主线程执行。
主线程优先级为 9,所以首先 t4.start() 应该被执行,但为什么 t.start() 会先被执行?
如果我颠倒调用 start 方法的顺序,即如果我按顺序调用 t4.start() 然后 t.start() 则输出符合预期。
输出
5
5
Main Thread Priority :9
5
Calling MyRunnable2 from main....9
Child Class - line 1
Child Class - line 2
End of Child loop - line 3
Calling MyRunnable2 from MyThread - line 4
MyRunnable2 Class....Main....9 - line 5
MyRunnable2 Class....From MyThread run....5
代码:-
public class ThreadPriority
{
public static void main(String[] args)
{
MyThread t = new MyThread();
System.out.println(Thread.currentThread().getPriority());
System.out.println(t.getPriority());
t.setName("From MyThread");
Thread.currentThread().setPriority(9);
System.out.println("Main Thread Priority :" + Thread.currentThread().getPriority());
System.out.println(t.getPriority());
MyRunnable2 r4 = new MyRunnable2();
Thread t4 = new Thread(r4,"Main");
System.out.println("Calling MyRunnable2 from main"+"...."+t4.getPriority());
t.start();
t4.start();
}
}
class MyRunnable2 implements Runnable
{
public void run()
{
System.out.println("MyRunnable2 Class"+"...."+Thread.currentThread().getName()+"...."+Thread.currentThread().getPriority());
}
}
class MyThread extends Thread
{
public void run()
{
for (int i=0;i<2;i++)
System.out.println("Child Class");
System.out.println("End of Child loop");
MyRunnable2 r2 = new MyRunnable2();
Thread t2 = new Thread(r2,"From MyThread run");
System.out.println("Calling MyRunnable2 from MyThread");
t2.start();
}
【问题讨论】:
-
因为优先级对于 Java 线程来说是一个有点坏的概念。这些数字是对操作系统的建议。真正发生的事情取决于实现/操作系统。
-
嗨@GhostCat这是否意味着我的理解是正确的并且上述行为是异常的?
-
不,这意味着您不应该使用线程优先级来确定执行顺序。如果您的代码依赖于线程优先级作为正确运行的要求,那么它可能已损坏。如果对您很重要,您应该使用同步或
java.util.concurrent。 -
使用线程优先级来确定调度顺序可能适用于单 CPU 机器(任何时候只有一个线程可以执行)。由于当前大多数计算机都有多个内核,因此能够并行运行多个线程,线程优先级的概念就更没用了。
标签: java multithreading thread-priority