A, first

Threads in Java are implemented through the java.lang.Thread class. The VM starts with a thread defined by the main method. You can create new threads by creating instances of Thread. Each Thread completes its operations through a method run() corresponding to a particular Thread object, called the Thread body. Start a Thread by calling the start() method of the Thread class.

In Java, threads typically have five states: created, ready, running, blocked, and dead.

The first is to create state. When a thread object is generated, the object’s start method is not called, which is the thread being created.

The second is readiness. When the start method of a thread object is called, the thread is ready, but the thread scheduler has not set the thread to the current thread. The thread is also in the ready state after it runs, after it comes back from waiting or sleeping.

The third is the running state. The thread scheduler sets the thread in the ready state to the current thread, at which point the thread enters the run state and starts running the code in the run function.

The fourth is blocking. A thread is suspended while it is running, usually to wait for a certain time to occur (such as when a resource is ready) before continuing. Methods like sleep,suspend, and wait can all cause threads to block.

The fifth is death. If a thread’s run method finishes or stops, the thread dies. For dead threads, you can no longer use the start method to get them ready.

Second, start () method

1. Why is the start method needed? What does it do?

The start () method is used to start the thread, truly implementing multithreading. The start method is used to change a thread from a NEW state to a RUNABLE state. When a thread is successfully created, it is in the NEW state. If you do not call the start() method, the thread is always in the NEW state. After you call start(), the thread becomes RUNABLE and can run.

Does the thread execute immediately after the start () method is called?

Threads do not execute immediately; Specifically, after the start() method is called, the thread is in the “READY” state, not the “RUNNING” state. Threads wait for CPU scheduling, different JVMS have different scheduling algorithms, and it is unknown when a thread will be scheduled. Therefore, the order in which the start () method is called does not determine the order in which threads are executed

Note: Since the state of a thread by NEW —-> RUNABLE occurs only once during its lifetime, a thread can only call the start () method once, and it is illegal to start a thread more than once. Especially if the thread has finished executing, it cannot be restarted.

The run() method

1. What is the run method? How does the run method relate to the start method?

The run() method calls run() as if it were a normal method, except that when a thread calls start(), it will only call the run() method once the thread is scheduled by the CPU and is running.

2. Does the run () method require the thread to call the start () method

As mentioned above, the run () method is a normal object method and therefore does not need to be called by the thread after starting (). Thread objects can call the Run method anytime, anywhere.

# Example1:

  Thread t1 = new Thread(new MyTask(1));
  Thread t2 = new Thread(new MyTask(2));
     t1.run();
     t2.run();
Copy the code

The output above is fixed:

The value of count is 1

Here’s another example:

 Thread t1 = new Thread(new MyTask());
 Thread t2 = new Thread(new MyTask());
     t1.start();
     t2.start();
Copy the code

The output is not fixed because the thread is unpredictable. The results may be different.

MyTask class:

// Implements Runnable; class MyTask implements Runnable{int count; public MyTask(int count) { this.count=count; } @Override public voidrun() {
        System.out.println("Count value:"+count); }}Copy the code

# Example2:

1. Start the thread with the start method

    public class Main {  
      
        public static void main(String[] args) {  
            Thread t1 = new Thread(new T1());  
            Thread t2 = new Thread(new T2());  
            t1.start();  
            t2.start();  
        }  
      
    }  
      
    class T1 implements Runnable {  
        public void run() {  
            try {  
                for(int i=0; i<10; i++){ System.out.println(i); Thread.sleep(100); }} catch (InterruptedException e) {e.printStackTrace(); } } } class T2 implements Runnable { public voidrun() {  
            try {  
                for(int i=0; i>-10; i--){ System.out.println(i); Thread.sleep(100); }} catch (InterruptedException e) {e.printStackTrace(); }}}Copy the code

Results:

Start (); run();

public class Main { public static void main(String[] args) { Thread t1 = new Thread(new T1()); Thread t2 = new Thread(new T2()); t1.run(); t2.run(); }}Copy the code

Conclusion:

From example 1 and example and we can know that the start method is used to start the thread, can achieve concurrency, while the run method is a common method, is not concurrent, only when the concurrent execution will be called.

Speaking of which, I don’t know if you understand the difference between these two methods. If you have any questions, please leave a message.

Start () and run();

    public synchronized void start() {// If thread is not"Ready state"Throws an exception!if(threadStatus ! = 0) throw new IllegalThreadStateException(); // Add a thread to a ThreadGroup. boolean started =false; Try {// Start the thread with start0(), and the new thread calls the run() method start0(); // Set the started flag =true  
            started = true;  
        } finally {  
            try {  
                if(! started) { group.threadStartFailed(this); } } catch (Throwable ignore) { } } }Copy the code
public void run() {  
    if (target != null) {  
        target.run();  
    }  
} 
Copy the code

Understand the Thread class

The Thread object is actually a Java object, but each Thread object corresponds to a Thread. The objects of the Thread class provide the user with information to manipulate and retrieve threads. The real underlying thread user is invisible. Therefore, when a Thread terminates and dies, the object of the corresponding Thread can still call all methods except start(), such as run(), getName(), getPriority () **, and so on

// For simplicity, use the method of the anonymous inner class to create a Thread Thread = newThread(){
        @Override
        public void run() {
            System.out.println("The Thread object's run method was executed."); }}; Thread.start (); // Use a loop to check if a thread is alive, and exit the loop only when the thread has terminatedwhile(thread.isalive ()){} // The thread is dead, but most methods of the thread object can still be called system.out.println ()"Thread"+thread.getName()+"State of:"+thread.getState()+"-- Priority:"+thread.getPriority()); // Call the run method thread.run(); Thread.start (); thread.start(); thread.start();Copy the code
The resources
  • http://www.cnblogs.com/jinggod/p/8485143.html
  • https://blog.csdn.net/u010568463/article/details/47911181
  • https://blog.csdn.net/xuxurui007/article/details/7685076

If there are any improper articles, please correct them. You can also follow my wechat official account: Learn Java well and get quality learning resources.