Home> Java> javaTutorial> body text

What is the difference between start and run in java thread

WBOY
Release: 2023-04-20 12:37:18
forward
1663 people have browsed it

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!

Related labels:
source:yisu.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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!