Java Threadクラス

Threadクラス

Threadクラスを利用する方式では、java.lang.Threadクラスを継承してrunメソッドを再定義(Overriding)します。runメソッドはスレッドが実行するメソッドであり、開発者はこのメソッドに実行するコードを記述します。

例1)Threadを1つ実行 次はThreadを継承してクラスを実装し、生成する例です。

package com.devkuma.tutorial.thread;

public class MyThread extends Thread {

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("This is thread. i=" + i);
        }
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

実行結果:

This is thread. i=0
This is thread. i=1
This is thread. i=2
This is thread. i=3
This is thread. i=4
This is thread. i=5
This is thread. i=6
This is thread. i=7
This is thread. i=8
This is thread. i=9

単に1つのスレッドが実行されるため、通常の繰り返し文と同じ結果になります。

例2)Threadを2つ実行

次は2つのスレッドを持つ場合を見てみます。

package com.devkuma.tutorial.thread;

public class MyThread2 extends Thread {

    public MyThread2(String name) {
        super(name);
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(super.getName() + " thread. i=" + i);
        }
    }

    public static void main(String[] args) {
        MyThread2 thread1 = new MyThread2("first");
        MyThread2 thread2 = new MyThread2("second");
        thread1.start();
        thread2.start();
    }
}

実行結果:

first thread. i=0
first thread. i=1
second thread. i=0
second thread. i=1
second thread. i=2
first thread. i=2
second thread. i=3
second thread. i=4
second thread. i=5
second thread. i=6
second thread. i=7
second thread. i=8
second thread. i=9
first thread. i=3
first thread. i=4
first thread. i=5
first thread. i=6
first thread. i=7
first thread. i=8
first thread. i=9

例1)と比較すると、first threadとsecond threadが不規則に実行され、それぞれの結果を表示していることがわかります。