Java多线程: cannot change thread priority

标签 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

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

最佳答案

您应该调用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/

相关文章:

java - 编写接受字符串并返回字符数组的方法时遇到问题

java - Android - OpenCV 错误 : Cannot load info library for OpenCV

java - 如何在线程内访问变量?

python - 程序立即终止,忽略守护线程中的 time.sleep()

c - 将参数传递给 pthread 会导致重复 C

linux - 一个进程的线程可以在多个物理 CPU 上运行?

java - 如何从源代码构建 Mojarra

java - 实体惰性方法和 Dimetra 法

c++ - 多个线程访问共享资源

php - Cs购物车产品查询很慢