Javaスレッド(Thread)Runnableインターフェース

Runnableインターフェース

Runnableインターフェースを利用する方式では、java.lang.Runnableインターフェースをimplementsで定義し、runメソッドを再定義(Overriding)します。先に見たThread継承方式と同じように、runメソッドにはスレッドが実行するコードを記述します。

例1)Threadを1つ

package com.devkuma.tutorial.thread;

public class MyRunnable implements Runnable {

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

    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        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

結果はThreadクラスの例1)と同じです。これもスレッドが1つだけなので、単純に繰り返しを実行した結果と同じになります。複数のスレッドを実行すると、複数のスレッドが同時に実行され、それぞれの結果を表示することになります。