Home >Java >javaTutorial >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
Thread start(): Thread Creation
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() { ... } }
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(); }
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(); }
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!