Java多线程:无法更改线程优先级

时间:2017-06-03 23:18:25

标签: java multithreading

我有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

即使具有不同的优先级,它也显示出类似的优先级。

1 个答案:

答案 0 :(得分:2)

您应该致电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