[Java Concurrency] 02: Runnable

One of the methods to run tasks in multiple thead is to pass Runnable instance to thread and call that start() method.

public class D_Runnable_Thread {

    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("start running task...");     
            }
        });
        
        t.start();
    }
}

Runnable is a Functional interface that has only one method that returns void.

If you prefer the lambda syntax, you can write the above code like so:

public class D_Runnable_Thread {

    public static void main(String[] args) {
        Thread t = new Thread(() -> System.out.println("start running task..."));

        t.start();
    }
}

However, for tasks with more than a few lines of code, you would prefer to create a class that implement Runnable.

Class implements Runnable

It’s quite simple to create a class implementing Runnable. You only need to implement the run() method:

public class D_Runtask implements Runnable{
    @Override
    public void run() {
        System.out.println("starting...");
        System.out.println("running...");
    }
}

Now, you can create an instance of this class and pass to a Thread to start the execution:

    public static void main(String[] args) {
        (new Thread(new D_Runtask())).start();
    }

Output:

Passing data into Runnable

In case you need to pass parameters to the job, simply pass them using constructor:


public class D_Runtask implements Runnable {
    private String name;
    public D_Runtask(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("starting..." + this.name);
        System.out.println("running..." + this.name);
    }

    public static void main(String[] args) {
        (new Thread(new D_Runtask("Super task"))).start();
    }
}

Output:

Leave a Comment