Home > Java > javaTutorial > Runnable run() vs. Thread start(): What's the Key Difference?

Runnable run() vs. Thread start(): What's the Key Difference?

Barbara Streisand
Release: 2024-12-21 22:55:31
Original
117 people have browsed it

Runnable run() vs. Thread start(): What's the Key Difference?

Runnable run() vs. Thread start()

Question:

In concurrent Java programming, the Runnable interface defines a run() method which is the entry point for a task. Similarly, the Thread class has a start() method that initiates a new thread of execution. What's the key difference between these two methods?

Answer:

The fundamental distinction lies in thread creation and execution:

Runnable run(): No Thread Creation

  • Calling Runnable.run() directly does not create a new thread.
  • Instead, it executes the run() method within the current thread of execution.
  • This approach is suitable when the task is lightweight and does not require its own dedicated thread.

Thread start(): Thread Creation

  • Calling Thread.start() initiates a new thread of execution.
  • Within the new thread, the run() method of the associated Runnable object is executed.
  • Using Thread.start() allows for parallelism by dividing the task into separate threads that run concurrently.

Example:

Consider two classes, R1 and R2, implementing the Runnable interface:

class R1 implements Runnable {
    public void run() { ... }
}

class R2 implements Runnable {
    public void run() { ... }
}
Copy after login

In the following code snippet, r1.run() and r2.run() are invoked directly, which means no new threads are created:

public static void main() {
    R1 r1 = new R1();
    R2 r2 = new R2();

    r1.run();
    r2.run();
}
Copy after login

In contrast, the following code creates two new threads, t1 and t2, and starts them:

public static void main() {
    R1 r1 = new R1();
    R2 r2 = new R2();
    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);

    t1.start();
    t2.start();
}
Copy after login

In this code, the tasks associated with r1 and r2 will be executed concurrently within the newly created threads.

The above is the detailed content of Runnable run() vs. Thread start(): What's the Key Difference?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template