The difference between start () and run () in thread
start () : Its role is to start a new thread, and the new thread executes the corresponding run () method. Start () cannot be called repeatedly.
Run () : Run () is the same as the normal member method and can be called repeatedly. Calling run () alone will execute run () in the current thread and will not start a new thread!
Mythreadtest.java Code
classMyThreadextendsthread{ Public voidrun () {System.out.println ("Thread Name:" +Thread.CurrentThread (). GetName ()); }} Public classMythreadtest { Public Static voidMain (string[] args) {MyThread MyThread=NewMyThread (); Mythread.start ();//Run Result: Thread Name: Thread-0Mythread.run ();//Run Result: Thread Name: Main }}
Result Description :
Thread.CurrentThread (). GetName () is the name used to get the "current thread". The current thread is the thread that is dispatching execution in the CPU.
Mythread.run () is called in the main thread main, and the Run () method runs directly on the main thread main.
Mythread.start () will start "Thread Mythread", and "thread Mythread" will invoke the run () method after it is started, and the Run () method at this time is run on thread mythread.
The start () method in the thread class source code
Public synchronized voidstart () {//throws an exception if the thread is not in the ready state! if(Threadstatus! = 0) Throw Newillegalthreadstateexception (); //to add a thread to the ThreadgroupGroup.add ( This); Booleanstarted =false; Try { //starting a thread with start0 ()start0 (); //Setting the started tagstarted =true; } finally { Try { if(!started) {group.threadstartfailed ( This); } } Catch(Throwable ignore) {} }}
description : Start () actually starts the thread through the local method Start0 (). Start0 () will run a new thread, and the new thread will call the run () method.
Thread class in the run source code
Private Runnable target;
public void run () { ifnull) { target.run ();} }
Description : Target is a runnable object. Run () is the run () method that calls the runnable member of the thread thread directly, and does not create a new thread.
Java Foundation Enhancement Concurrency (iii) The difference between start () and run () in thread