Home > Java > javaTutorial > In Java, when to call Thread.run() instead of Thread.start()?

In Java, when to call Thread.run() instead of Thread.start()?

WBOY
Release: 2023-09-15 12:13:02
forward
1233 people have browsed it

In Java, when to call Thread.run() instead of Thread.start()?

When we call the start() method on a thread, it causes the thread to start executing, and the thread's run() The method will be called Java Virtual Machine (JVM). If we call the run() method directly, it will be treated as a normal overridden method of the thread class (or runnable interface), and it will be Executed in the context of the current thread rather than in a new thread.

Example

public class CallRunMethodTest extends Thread {
   @Override
   public void run() {
      System.out.println("In the run() method: " + Thread.currentThread().getName());
      for(int i = 0; i < 5 ; i++) {
         System.out.println("i: " + i);
         try {
            Thread.sleep(300);
         } catch (InterruptedException ie) {
            ie.printStackTrace();
         }
      }
  }
   public static void main(String[] args) {
      CallRunMethodTest t1 = new CallRunMethodTest();
      CallRunMethodTest t2 = new CallRunMethodTest();
      t1.run(); <strong>// calling run() method directly instead of start() method</strong>
      t2.run(); <strong>// calling run() method directly instead of start() method</strong>
   }
}
Copy after login

In the above example, two threads are created and the run() method is called directly on the threads instead of calling the start() method.

Output

In the run() method: main
i: 0
i: 1
i: 2
i: 3
i: 4
In the run() method: main
i: 0
i: 1
i: 2
i: 3
i: 4
Copy after login

The above is the detailed content of In Java, when to call Thread.run() instead of Thread.start()?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template