更改线程优先级没有效果

时间:2012-01-26 13:55:17

标签: android thread-priority

我正在尝试使用android.os.Process.setThreadPriority()更改主线程的优先级。我在优先级更改之前和之后都有日志消息,这里是代码:

public class TestActivity extends Activity {
    public final String TAG="TestActivity";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        int tid=(int)Thread.currentThread().getId();
        Log.d(TAG,"priority before change = " + android.os.Process.getThreadPriority(tid));
        Log.d(TAG,"priority before change = "+Thread.currentThread().getPriority());
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY);
        Log.d(TAG,"priority after change = " + android.os.Process.getThreadPriority(tid));
        Log.d(TAG,"priority after change = " + Thread.currentThread().getPriority());
    }
}

我得到以下输出:

priority before change (getThreadPriority) = 0
priority before change (currentThread().getPriority) = 5
priority after change (getThreadPriority) = 0
priority after change (currentThread().getPriority) = 5

这意味着优先级没有改变,无论我用什么方法来评估它。 android.os.Process.THREAD_PRIORITY_DISPLAY = -4,所以改变我的输出后应该等于-4,为什么它保持不变?为什么android.os.Process.setThreadPriority()无效?

P.S。我阅读了有关线程的谷歌文档,但我没有遇到任何解释android.os.Process.getThreadPriority()Thread.currentThread().getPriority()之间差异的问题。为什么这些方法会返回不同的值?

P.P.S。 Thread.currentThread().setPriority()工作正常。

1 个答案:

答案 0 :(得分:11)

您使用错误的ThreadID进行检查。

要获得正确的ID,您必须使用android.os.Process.myTid();

固定代码:

package mypackage.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class TestActivity extends Activity {
    public final String TAG="TestActivity";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        int tid=android.os.Process.myTid();

        Log.d(TAG,"priority before change = " + android.os.Process.getThreadPriority(tid));
        Log.d(TAG,"priority before change = "+Thread.currentThread().getPriority());
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY);
        Log.d(TAG,"priority after change = " + android.os.Process.getThreadPriority(tid));
        Log.d(TAG,"priority after change = " + Thread.currentThread().getPriority());
    }
}

日志输出:

priority before change = 0
priority before change = 5
priority after change = -4
priority after change = 5

供进一步参考:

http://developer.android.com/reference/android/os/Process.html#myTid()