java - 当在线程对象上调用 start 时,在线程上设置的优先级不起作用

标签 java multithreading

我执行了以下代码:

public class TestMain extends Thread{

    public static Runnable getRunnableObject(){
        Runnable r = new Runnable(){
            @Override
            public void run() {
                System.out.println("inside runnable");
            }
        };

        return r;           
    }

    public static void main(String args[]){
        Thread t2 = new Thread(getRunnableObject());
    //  t2.start();
        System.out.println("name "+t2.getName()+" id "+t2.getPriority()+" class "+t2.getClass()
                +" priortity "+t2.getPriority()+" state "+t2.getState()+" alive/dead "+t2.isAlive());

        System.out.println("runtime"+Runtime.getRuntime().availableProcessors());
        t2.setPriority(MAX_PRIORITY);
        System.out.println(t2.getPriority());

        t2.setPriority(MIN_PRIORITY);
        System.out.println(t2.getPriority());

        t2.setPriority(NORM_PRIORITY);
        System.out.println(t2.getPriority());
    }
}

输出:

name Thread-0 id 5 class class java.lang.Thread priortity 5 state NEW alive/dead false
runtime4
10
1
5

现在我再次运行它,取消第 22 行代码的注释。

输出2:

inside runnable
name Thread-0 id 5 class class java.lang.Thread priortity 5 state RUNNABLE alive/dead true
runtime4
5
5
5

你能告诉我为什么当我在线程上调用 start() 时设置优先级不起作用吗?

最佳答案

这是一个竞争条件。

当您尝试设置t2的优先级时,它已经死了。 如果您将 Runnable 更改为阻塞一段时间,如下所示:

Runnable r = new Runnable() {

    @Override
    public void run() {
        System.out.println("inside runnable");
        try {
            Thread.sleep(100000);
        } catch (InterruptedException e) {
           //
        }
    }
}

然后您将得到相同的序列 10, 1, 5。

关于java - 当在线程对象上调用 start 时,在线程上设置的优先级不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633348/

相关文章:

java - isPalindrome - 集合和列表反转

java - 故障排除和修复死锁

Java 线程中断标志被清除

python - 如何停止执行器中的循环运行?

java - Alertdialog.Builder 的 setItems() onClick 返回空对话框

javafx单击其他节点时不会失去焦点

java - 单例 Swing 组件

java - 防止 MySQL JDBC 驱动程序将 DateTime 转换为本地时间

java - 为什么放置 start() 命令时会有所不同?

c++ - c/c++ Linux 允许的最大互斥量