Home  >  Article  >  Java  >  What is the difference between start and run in java thread

What is the difference between start and run in java thread

WBOY
WBOYforward
2023-04-20 12:37:181602browse

public class Test1 extends Thread {

@Override public void run() {

while (true)

{

System.out. println(Thread.currentThread().getName());

}

}

public static void main(String[] args) {

Test1 test1=new Test1();

test1.run(); //Output result main

test1.start(); //Output result Thread-0

}

}

1.start

start is to start a new thread.

When start() is used to start a thread, the thread enters the ready state, making the virtual processor represented by the thread in a runnable state, which means that it can be scheduled and executed by the JVM. But this does not mean that the thread will run immediately. Only when the CPU allocates a time slice and this thread obtains the time slice, does it start executing the run() method. start() cannot be called repeatedly, it calls the run() method. The run() method is what you must override

2.run

run() just Like ordinary member methods, they can be called repeatedly.

If you call the run method directly, a new thread will not be started! There is still only one thread in the program, the main thread, and there is still only one program execution path. It still needs to be executed sequentially, and it still needs to wait for the run method body to be executed before continuing to execute the following code. In this way, the purpose of multi-threading is not achieved.

Call the start method to start the thread, and the run method is just a normal method call of thread, which is still executed in the main thread.

The above is the detailed content of What is the difference between start and run in java thread. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete