SoFunction
Updated on 2025-04-08

Java example code to create threads using Runnable interface

1. What is the Runnable interface?

Runnableis a functional interface in Java, defined inIn the package. It contains only one abstract methodrun(), This method is used to define tasks executed by threads.RunnableThe interface is defined as follows:

@FunctionalInterface
public interface Runnable {
    void run();
}

becauseRunnableis a functional interface, so it can be implemented using Lambda expressions, which makes the code more concise.

2. Steps to create threads using Runnable interface

useRunnableThe steps for creating threads in the interface are as follows:

  1. Implementing the Runnable interface: Create a class and implement itRunnableInterface, or directly implement it using Lambda expressionsRunnableinterface.
  2. Rewrite the run method:existrun()The method defines the task that the thread wants to execute.
  3. Create Thread object:WillRunnableThe instance is passed as a parameter toThreadThe constructor of the class.
  4. Start the thread: CalledThreadThe object'sstart()Method starts the thread.

2.1 Sample Code

Here is a simple example showing how to use itRunnableInterface creation thread:

public class RunnableExample implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            (().getName() + " - " + i);
        }
    }

    public static void main(String[] args) {
        // Create a Runnable instance        RunnableExample runnableExample = new RunnableExample();

        // Create Thread object        Thread thread = new Thread(runnableExample);

        // Start the thread        ();

        // The main thread continues to execute        for (int i = 0; i < 5; i++) {
            (().getName() + " - " + i);
        }
    }
}

2.2 Simplify code using Lambda expressions

becauseRunnableIt is a functional interface that we can use Lambda expressions to simplify the code:

public class RunnableLambdaExample {

    public static void main(String[] args) {
        // Implement the Runnable interface using Lambda expression        Runnable runnable = () -> {
            for (int i = 0; i < 5; i++) {
                (().getName() + " - " + i);
            }
        };

        // Create Thread object        Thread thread = new Thread(runnable);

        // Start the thread        ();

        // The main thread continues to execute        for (int i = 0; i < 5; i++) {
            (().getName() + " - " + i);
        }
    }
}

3. Advantages of Runnable interface

and direct inheritanceThreadCompared with the class, useRunnableInterface creation threads have the following advantages:

3.1 Avoid single inheritance restrictions

Java does not support multiple inheritance. If a class has inherited other classes, it cannot be inherited.Threadkind. And achieveRunnableThere is no such limitation for interfaces, because a class can implement multiple interfaces.

3.2 Better code reuse

By implementingRunnableInterfaces can separate thread logic from thread creation and management. In this way, the sameRunnableInstances can be shared by multiple threads, thereby improving code reusability.

3.3 More in line with object-oriented design principles

useRunnableThe interface is more in line with the principle of object-oriented design, because it will task (Runnable) and threads that execute tasks (Thread) separate. This separation makes the code more flexible and maintainable.

4. Use scenarios of Runnable interface

RunnableThe interface is suitable for the following scenarios:

  • Concurrent tasks need to be performed: When the program needs to execute multiple tasks at the same time, it can be usedRunnableInterface creates multiple threads.
  • Shared resources are required: Multiple threads can share the sameRunnableinstances, thus sharing resources.
  • Need thread pool management: When using thread pools, usuallyRunnableTasks are submitted to thread pool for execution.

5. Summary

By implementingRunnableInterface creation threads are a common and recommended way of Java multithreading programming. It not only avoids the limitation of single inheritance, but also improves the reusability and flexibility of the code. Whether it is simple concurrent tasks or complex thread management,RunnableAll interfaces can provide strong support.

In actual development, it is recommended to use it firstRunnableInterfaces to create threads, especially in scenarios where sharing resources or using thread pools are required. By masteringRunnableWith the use of interfaces, you will be able to write more efficient and maintainable multi-threaded programs.

The above is the detailed content of the sample code for Java using the Runnable interface to create threads. For more information about Java Runnable creating threads, please follow my other related articles!