【问题标题】:Why does this code give this output for the thread's priority?为什么这段代码会为线程的优先级提供这个输出?
【发布时间】:2023-03-17 22:53:01
【问题描述】:

我有以下代码onCreate()

Log.d(TAG, "Setting priority background");  
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
Log.d(TAG, Thread.currentThread().getId() + ": " + Thread.currentThread().getPriority());
Log.d(TAG, Process.getThreadPriority(Process.myTid()) + " - myTid() " + Process.myTid() + " Thread.getId() = " + Thread.currentThread().getId());
// start a thread here
Thread thread = new Thread(() -> {
            Log.d(TAG, " In new thread");
            Log.d(TAG, Thread.currentThread().getId() + ": " +   Thread.currentThread().getPriority());
            Log.d(TAG, Process.getThreadPriority(Process.myTid()) + " - myTid() " + Process.myTid() + "Thread.getId() = " + Thread.currentThread().getId());

}  

输出是:

Setting priority background  
1: 5  
10 - myTid() 8798 Thread.getId() = 1  

In new thread  
7534: 10  
-8 - myTid() 8819 Thread.getId() = 7534 

谁能解释一下:
1) 即使我设置了setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);,下一行中的日志也会显示优先级5。为什么?
2) 第二个线程的优先级输出中的-8 来自哪里?
3) 新线程的10 也是从哪里来的?

更新:
如果我删除行 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
输出保持不变

【问题讨论】:

    标签: java android multithreading linux-kernel android-threading


    【解决方案1】:

    读取hereTHREAD_PRIORITY_BACKGROUND 将低于正常的优先级委派给该线程上的任务。

    here 获取信息,使用Thread.setPriority() 包含从MIN_PRIORITY(1) 到MAX_PRIORITY(10) 的值 Process.setThreadPriority() 支持从-20 到19 的值。

    下图显示了 Android 调度程序和 Linux 调度程序及其优先级。调用 ProcessThread 来获取线程优先级将返回两个不同的值,因为它们是两个不同的调度程序,就像在您的日志中一样。

    更新:

    This 的帖子对此提供了一些见解:

    • Process.myTid() 是 linux 线程 ID
    • Thread.getId() 是一个简单的 连续长数字。

    “Thread.getId() 只是一个“java 层”静态长,为每个线程自动递增。”

    ThreadID 不等于 ProcessID。

    但是,将 long 转换为 int 并将 ThreadID 提供给进程会返回预期值 Process.getThreadPriority((int) Thread.currentThread().getId())

    【讨论】:

    • 尽管我相信该映射并不能解释值 -8 的来源
    • 也按照映射5 <=> 0,但打印了10
    • 更新了更多信息。
    • 感谢您的更新,但我没有使用Process.getThreadPriority((int) Thread.currentThread().getId())。这个怎么称呼?
    • 我的意思是我没有在任何地方做Process.getThreadPriority((int) Thread.currentThread().getId())。为什么这会影响某些事情?
    猜你喜欢
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多