Java Thread Runnable Interface

Runnable Interface

The approach using the Runnable interface defines java.lang.Runnable with implements and overrides the run method. As with the Thread inheritance approach shown earlier, write the code the thread should execute in the run method.

Example 1) One Thread

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();
    }
}

The result is as follows.

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

The result is the same as Example 1 of the Thread class. Since there is only one thread, the result is the same as simply running a loop. If multiple threads are executed, several threads will run at the same time and display their own results.