JAVA-TRICK-3: What Happens If You Call the Run Method Directly Instead of Start()?

JAVA-TRICK-3: What Happens If You Call the Run Method Directly Instead of Start()?

Question:

What is the difference between calling run() and start() for a thread?

Explanation:

  • Calling start() creates a new thread and executes the run() method in that thread.
  • Calling run() directly executes the code in the current thread without starting a new thread.

Example:

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}
public class Test {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.run(); // Executes in main thread
        t1.start(); // Executes in a new thread
    }
}        

Output:

Thread running
Thread running        

要查看或添加评论,请登录

Chamseddine Toujani的更多文章

社区洞察

其他会员也浏览了