Jim
Jim

Reputation: 4425

Why does this code give this output for the thread's priority?

I have the following code 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());

}  

The output is:

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

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

Can someone please explain:
1) Even though I set setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); the log in the next line shows priority 5. Why?
2) Where is the -8 coming from in the output for the priority of the second thread?
3) Where is the 10 for the new thread coming from too?

Update:
If I remove the line Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
the output remains the same

Upvotes: 2

Views: 355

Answers (1)

JakeB
JakeB

Reputation: 2113

Reading here, THREAD_PRIORITY_BACKGROUND delegates a lower than normal priority to the task on that thread.

Taking information from here, using Thread.setPriority() contains a value from MIN_PRIORITY(1) to MAX_PRIORITY(10) whereas Process.setThreadPriority() supports value from -20 to 19.

The image below shows the Android Scheduler and the Linux Scheduler and their priority levels. Calling Process and Thread to get thread priority will return two diffrent values as they are two different schedulers, like in your logs.

enter image description here

Update:

This post provided some insight into this:

  • Process.myTid() is the linux thread ID
  • Thread.getId() is a simple sequential long number.

"Thread.getId() is simply a "java layer" static long being auto-increment for each thread."

ThreadID is not equal to ProcessID.

However, casting the long to int and providing the ThreadID to the Process returns an expcted value Process.getThreadPriority((int) Thread.currentThread().getId()).

Upvotes: 2

Related Questions