The differences between the run () and start () methods in the Thread class are as follows:
Run () method: the run () method of the Runnable object can be called multiple times in this thread;
Start () method: start a thread and call the run () method of the Runnable object. A thread cannot be started multiple times;
Package com. ljq. test;
Public class ThreadTest {
/**
* Observe the difference between calling run () directly and starting a thread with start ()
*
* @ Param args
* @ Throws Exception
*/
Public static void main (String [] args ){
Thread thread = new ThreadDemo ();
// First
// Indicates that the run () method is not different from the call of other methods. The main method executes it in order and prints the last sentence.
// Thread. run ();
// Type 2
// Indicates that the start () method re-creates a thread. After the main method is executed, the thread created by the start () method is not running,
// Therefore, the main thread fails to exit until the thread is executed. Note that the thread created by default is a user thread (non-daemon thread)
// Thread. start ();
// The third type
// 1. Why didn't 100 sentences be printed? Because we set the thread to a daemon thread, the program can exit only when the daemon thread exists, so we exit after printing only seven sentences.
// 2. When a daemon thread in the Java virtual machine is running, the Java Virtual Machine is closed. After all the general threads have finished running,
// No matter where the daemon thread runs, the VM will exit. Therefore, it is recommended that you do not write some daemon threads that will affect the business logic of the program. Otherwise, you cannot predict what problems the program will encounter.
// Thread. setDaemon (true );
// Thread. start ();
// Category 4
// The user thread can be forced to kill by System. exit (0), so only seven sentences can be printed.
Thread. start ();
System. out. println ("main thread is over ");
System. exit (1 );
}
Public static class ThreadDemo extends Thread {
@ Override
Public void run (){
For (int I = 0; I <100; I ++ ){
System. out. println ("This is a Thread test" + I );
}
}
}
}