解説
プログラムでは、複数の処理内容を並行して実行したい場合があります。そういった際に、プログラムの最小の処理内容の単位を「スレッド」と呼びます。
スレッドを使えば、例えば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
この記事は参考になりましたか?
既に会員の方はを行ってください。
- マンガで分かるプログラミング用語辞典連載記事一覧
- この記事の著者
-
柳井 政和(ヤナイ マサカズ)
クロノス・クラウン合同会社 代表社員http://crocro.com/オンラインソフトを多数公開。プログラムを書いたり、ゲームを作ったり、記事を執筆したり、マンガを描いたり、小説を書いたりしています。「めもりーくりーなー」でオンラインソフト大賞に入賞。最近は、小説家デビューして小説も書いています(『裏切りのプログラム』他)。面白いことなら何でもOKのさすらいの企画屋です。
※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です
この記事は参考になりましたか?
この記事をシェア
