안 드 로 이 드 설정 스 레 드 우선 순위 두 가지 방식

더 읽 기
 
다음으로 이동: http://www.eoeandroid.com/thread-112252-1-1.html
1)android.os.Process.setThreadPriority(int priority)또는 android.os.Process.setThreadPriority(int tid,int priority)priority:[-20,19],높 은 우선 순위->낮은 우선 순위.(2)java.lang.Thread.setPriority(int priority)priority:[1,10],낮은 우선 순위->높 은 우선 순위.테스트 결과,안 드 로 이 드 자체 API(첫 번 째 방법)설정 의 우선 순 위 를 사용 하면 스 레 드 스케줄 에 현저 한 영향 을 줍 니 다.
------------------------------------------------
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;

public class TestThreadPriority extends Activity {
	private static final String TAG = "TestThreadPriority";

	private boolean mNeedExit = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		MyThread a = new MyThread("Thread A");
		a.setOSPriority(Process.THREAD_PRIORITY_LOWEST); // 19
		a.setPriority(Thread.MAX_PRIORITY); // 10

		MyThread b = new MyThread("Thread B");
		b.setOSPriority(Process.THREAD_PRIORITY_URGENT_AUDIO); // -19
		b.setPriority(Thread.MIN_PRIORITY); // 1

		a.start();
		b.start();
	}

	@Override
	public void onBackPressed() {
		mNeedExit = true;
		super.onBackPressed();
	}

	private class MyThread extends Thread {
		private int mOSPriority = Process.THREAD_PRIORITY_DEFAULT;
		private int mLoopCount = 0;

		public MyThread(String threadName) {
			super(threadName);
		}

		public void setOSPriority(int p) {
			mOSPriority = p;
		}

		@Override
		public void run() {
			Process.setThreadPriority(mOSPriority);

			while (!mNeedExit) {
				mLoopCount++;
				Math.log(Math.random() * 1000); // calculation test

				Log.d(TAG,
						new StringBuilder().append(getName())
								.append(" os priority: ").append(mOSPriority)
								.append(" java priority: ")
								.append(getPriority()).append(" loop count: ")
								.append(mLoopCount).toString());
			}

			Log.d(TAG,
					new StringBuilder().append(getName()).append(" exiting...")
							.append(" os priority: ").append(mOSPriority)
							.append(" java priority: ").append(getPriority())
							.append(" loop count: ").append(mLoopCount)
							.toString());
		}
	}
}
 

좋은 웹페이지 즐겨찾기