我有 2 个线程,其优先级已使用 setPriority()
函数设置,但它仍然显示相同的优先级?
这是代码片段:
public class threadtest extends Thread {
public void run() {
System.out.println("running thread name is:" + Thread.currentThread().getName());
System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
threadtest tt = new threadtest();
tt.setPriority(MAX_PRIORITY);
threadtest tt1 = new threadtest();
tt1.setPriority(MIN_PRIORITY);
tt1.run();
tt.run();
}
}
如果上述代码在我的 ECLIPSE neon 中的输出是。
running thread name is:main
running thread priority is:5
running thread name is:main
running thread priority is:5
即使有不同的优先级,它也显示出相似的优先级。
最佳答案
您应该调用Thread.start()
,而不是Thread.run()
。
当直接调用run()
方法时,run()
方法中的代码不会在新线程上执行,而是在同一个线程。另一方面,当您调用 Thread.start()
方法时,run()
方法中的代码将在实际创建的新线程上执行通过 start()
方法:
public class threadtest extends Thread {
public void run() {
System.out.println("running thread name is:" + Thread.currentThread().getName());
System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
threadtest tt = new threadtest();
tt.setPriority(MAX_PRIORITY);
threadtest tt1 = new threadtest();
tt1.setPriority(MIN_PRIORITY);
tt1.start();
tt.start();
}
}
输出:
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:10
running thread priority is:1
关于Java多线程: cannot change thread priority,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349371/