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.
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> } }
In the above example, two threads are created and the run() method is called directly on the threads instead of calling the start() method.
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
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!