解説
プログラムでは、複数の処理内容を並行して実行したい場合があります。そういった際に、プログラムの最小の処理内容の単位を「スレッド」と呼びます。
スレッドを使えば、例えばUIの処理を担当するスレッドと、その裏でデータを読み込んで処理するスレッドのように、異なった内容の処理を、スレッドごとにまとめて実行することができます。
また、最近のマルチコアCPUやGPUを利用して、複数の処理を同時に実行するようなことも可能になります。
プログラム内で、スレッドが1つだけの場合はシングルスレッドと呼びます。2つ以上の場合はマルチスレッドと呼びます。
サンプル
マルチスレッドのプログラムをJavaで書いてみます。
package sample;
public class MainClass {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 16; i ++) {
System.out.println("@thread1@ : " + i);
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 16; i ++) {
System.out.println("#thread2# : " + i);
}
}
});
thread1.start();
thread2.start();
}
}
#thread2# : 0 #thread2# : 1 #thread2# : 2 @thread1@ : 0 #thread2# : 3 @thread1@ : 1 @thread1@ : 2 @thread1@ : 3 #thread2# : 4 #thread2# : 5 #thread2# : 6 #thread2# : 7 #thread2# : 8 @thread1@ : 4 @thread1@ : 5 @thread1@ : 6 @thread1@ : 7 @thread1@ : 8 @thread1@ : 9 #thread2# : 9 @thread1@ : 10 @thread1@ : 11 #thread2# : 10 @thread1@ : 12 @thread1@ : 13 #thread2# : 11 @thread1@ : 14 @thread1@ : 15 #thread2# : 12 #thread2# : 13 #thread2# : 14 #thread2# : 15
