解答例 - 実習課題1 - 4.スレッドの制御
(実習課題1)
2章の実習課題2のプログラムで以下の点を試しなさい。可能であればLinuxとWindowsの両方で動作させ、優先度を設定したときの動作に違いがあるかどうかを確認すること。
- それぞれのスレッドに異なる優先度を設定する事。
- 設定した優先度の違いに応じて、結果がどのようになるか確かめる事。
解答例
/**
* BubbleSortImp.java
* TECHSCORE Java マルチスレッドプログラミング4章 実習課題1
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.thread.chapter4.exercise1;
public class BubbleSortImp implements Runnable {
private int[] array = new int[ThreadSpeadExample.LENGTH];
public void run() {
System.out.println("バブルソート開始");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
}
System.out.println("バブルソート終了");
}
public void setArray(int[] array) {
this.array = array;
}
}
/**
* ChoiceSortImp.java
* TECHSCORE Java マルチスレッドプログラミング4章 実習課題1
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.thread.chapter4.exercise1;
public class ChoiceSortImp implements Runnable {
private int[] array = new int[ThreadSpeadExample.LENGTH];
public void run() {
System.out.println("選択ソート開始");
for (int i = 0; i < array.length; i++) {
int min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[min] > array[j]) {
min = j;
}
}
if (min != i) {
int tmp = array[i];
array[i] = array[min];
array[min] = tmp;
}
}
System.out.println("選択ソート終了");
}
public void setArray(int[] array) {
this.array = array;
}
}
/**
* ThreadSpeadExample.java
* TECHSCORE Java マルチスレッドプログラミング4章 実習課題1
*
* Windowsでは優先度に従った結果が多いが、Linuxでは無視される
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.thread.chapter4.exercise1;
import java.util.Random;
public class ThreadSpeadExample {
public static final int LENGTH = 20000;
public static void main(String[] args) {
ChoiceSortImp choice = new ChoiceSortImp();
BubbleSortImp bubble = new BubbleSortImp();
//選択ソートスレッド
Thread choiceThread = new Thread(choice);
//バブルソートスレッド
Thread bubbleThread = new Thread(bubble);
//同じ値を持つ配列を作る
int[] array1 = new int[LENGTH];
int[] array2 = new int[LENGTH];
for (int i = 0; i < LENGTH; i++) {
array1[i] = new Random().nextInt(1000); //1000以下のランダムな値を代入
array2[i] = array1[i]; //同じ値をarray2にも代入
}
//配列をセットする
choice.setArray(array1);
bubble.setArray(array2);
//優先度を設定
choiceThread.setPriority(3);
bubbleThread.setPriority(7);
System.out.println("選択ソート優先度:" + choiceThread.getPriority());
System.out.println("バブルソート優先度:" + bubbleThread.getPriority());
//よーい、どん!
bubbleThread.start();
choiceThread.start();
}
}
■Windowsでの実行結果
------------------------------------------------------------
選択ソート優先度:3
バブルソート優先度:7
バブルソート開始
バブルソート終了
選択ソート開始
選択ソート終了
■Linuxでの実行結果
------------------------------------------------------------
選択ソート優先度:3
バブルソート優先度:7
バブルソート開始
選択ソート開始
選択ソート終了
バブルソート終了
■結論
------------------------------------------------------------
Windowsでは優先度に従った結果になることが多いが、Linuxでは完全に無視される

