Java : Runnable with Examples

Runnable (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Runnable methods.


Summary

Represents an operation that does not return a result.

Class diagram

try (final var executor = Executors.newSingleThreadExecutor()) {
    final var task = new Runnable() {
        @Override
        public void run() {
            System.out.println("Run!");
        }
    };

    System.out.println("-- submit --");
    executor.submit(task);
}

// Result
// ↓
//-- submit --
//Run!

Methods

void run ()

Runs this operation.

final var runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Run!");
    }
};

runnable.run(); // Run!

An example of lambda expression.

try (final var executor = Executors.newSingleThreadExecutor()) {
    System.out.println("-- submit --");
    executor.submit(() -> {
        System.out.println("Run!");
    });
}

// Result
// ↓
//-- submit --
//Run!

Related posts

Thread

Functional interface

To top of page