13

我正在尝试使用更改主线程的优先级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()没有效果?

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

PPSThread.currentThread().setPriority()工作正常。

4

1 回答 1

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()

于 2012-02-22T12:07:22.983 回答