Thread starting method start () and run ()

1.start
use the start method to achieve a truly multi-threaded operation, because directly continue with the following code uses the start () method without waiting for the run method body code is completed.
Because there are five kinds of thread thread state, create - Ready - running - blocked - five deaths, with start () method of the Thread class to start a thread, then this thread is ready (to run) state, and is not running, By the time cpu idle, the thread will be performed inside the run method, run method has finished running, the end of this thread.

2.run
because the method is run inside a thread of common method, the direct method calls the run, this time it is run in our main thread, the main thread of the program is still only this one thread, the program execution path or just one, or to execute the order, or to wait after the implementation of the run method body to proceed with the following code, so there is no purpose to write thread.

Code Example:

public class ThreadDemo {
    public static void main(String[] args){
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());
        thread1.start();
        thread2.start();
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
                Thread.sleep(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Two threads are using the open method of start, there is no need to wait for another to complete, so their order should be executed in parallel, we run look at the results:
Here Insert Picture Description
like us analyze, then we change to change code execution use run method, to see if the order of execution

 public static void main(String[] args){
    Thread thread1 = new Thread(new MyRunnable());
    Thread thread2 = new Thread(new MyRunnable());
    thread1.run();
    thread2.run();
}

Here Insert Picture Description
Summary: The start method is called before starting a thread, but just an ordinary run method calls the method thread, or executed in the main thread.

Reference: HTTPS: //my.oschina.net/134596/blog/1663837
https://blog.csdn.net/woshizisezise/article/details/79938915

Published 59 original articles · won praise 15 · views 559

Guess you like

Origin blog.csdn.net/qq_45287265/article/details/105054033