Created
September 4, 2013 13:22
-
-
Save amay077/6436867 to your computer and use it in GitHub Desktop.
スレッドの優先度について調べた ref: http://qiita.com/amay077/items/c2f7db34976e8d2a16ac
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 指定した Priority の ThreadFactory を生成して返す | |
| private ThreadFactory makeThreadFactory(final int priority) { | |
| return new ThreadFactory() { | |
| @Override | |
| public Thread newThread(Runnable r) { | |
| Thread thread = new Thread(r); | |
| thread.setPriority(priority); | |
| return thread; | |
| } | |
| }; | |
| } | |
| // 使ってみる | |
| private void testExecutor() { | |
| final ExecutorService executor = | |
| Executors.newSingleThreadExecutor(makeThreadFactory(Thread.MIN_PRIORITY)); | |
| executor.submit(new Runnable() { | |
| @Override | |
| public void run() { | |
| // なにかの処理 | |
| } | |
| }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private ThreadFactory makeThreadFactory(final int priority) { | |
| // 上と同じなので省略 | |
| } | |
| // タスクを生成する | |
| private Runnable makeTask(final String tag, final StringBuffer buffer, | |
| final CountDownLatch latch) { | |
| return new Runnable() { | |
| @Override | |
| public void run() { | |
| // タスクが開始された時に、A or B or C を追加してく | |
| buffer.append(tag); // StringBuffer は Thread-safe なハズだ | |
| // Wait | |
| for (int j = 0; j < 1000000; j++) { } | |
| latch.countDown(); | |
| } | |
| }; | |
| } | |
| // 検証実行 | |
| public void testThreadPriority() throws InterruptedException { | |
| // MIN, NORMAL, MAX な Priority の Executor を生成 | |
| final ExecutorService minExecutor = | |
| Executors.newSingleThreadExecutor(makeThreadFactory(Thread.MIN_PRIORITY)); | |
| final ExecutorService norExecutor = | |
| Executors.newSingleThreadExecutor(makeThreadFactory(Thread.NORM_PRIORITY)); | |
| final ExecutorService maxExecutor = | |
| Executors.newSingleThreadExecutor(makeThreadFactory(Thread.MAX_PRIORITY)); | |
| final CountDownLatch latch = new CountDownLatch(100 * 3); | |
| final StringBuffer builder = new StringBuffer(); | |
| // それぞれの Executor にじゃんじゃんタスクを投入 | |
| for (int i = 0; i < 100; i++) { | |
| minExecutor.submit(makeTask("C", builder, latch)); // MIN->"C" | |
| norExecutor.submit(makeTask("B", builder, latch)); // NORMAL->"B" | |
| maxExecutor.submit(makeTask("A", builder, latch)); // MAX->"A" | |
| } | |
| // 全部のタスクが終わるのを待つ | |
| latch.await(); | |
| Log.d(TAG, builder.toString()); // タスクが処理された順番を出力 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment