The start () method and the Run () method of the threading thread class

Source: Internet
Author: User
Tags thread class

First, initial knowledge

Java threads are implemented through java.lang.Thread classes. When the VM starts, it has a thread defined by the main method. You can create a new thread by creating an instance of the thread. Each thread does its work by means of the method that corresponds to a particular thread object run() , and the method run () is called the thread body. Start a thread by calling the method of the thread class start() .

In Java, threads typically have five states of creation, readiness, operation, blocking, and death.

The first is the creation State . In the build thread object, there is no call to the object's Start method, which is the thread in the created state.

The second is the ready state . When the start method of the thread object is called, the thread enters the ready state, but at this point the thread dispatcher has not set the thread to the current thread and is in a ready state. After a thread is running, it is ready to return from waiting or sleeping.

The third is the running state . The thread dispatcher sets the thread in the ready state to the current thread, and the thread enters the running state and starts running the code in the Run function.

The four is the blocking state . A thread is paused when it is running, usually in order to wait for a certain time to occur (for example, a resource is ready) before it continues to run. Methods such as sleep,suspend,wait can cause thread blocking.

Five is the state of Death . If a thread's Run method finishes executing or calls the Stop method, the thread dies. For a thread that has died, the start method can no longer be used to get it ready.

Second, start () method

1. Why the Start method is needed; what is its role?

Start () method to start the thread and really implement multi-threaded operation.
The Start method acts by changing the thread from the new state to the runable state. When a thread is created successfully, the thread is in the new state, and if you do not call the start () method, the thread is always in the new state. When start () is called, the thread will not be able to run until the runable state is changed.

2. After calling the start () method, does the thread execute immediately?

The thread is not executed immediately; after the start () method is called, the state of the thread is "ready" instead of the "RUNNING (running)" state (details about the state of the thread). Threads are waiting for CPU scheduling, different JVMs have different scheduling algorithms, and when threads are scheduled is unknown. Therefore, the call order of the start () method does not determine the order in which the threads are executed

Attention:
Because the state of a thread is only one time from the new ----> runable in the life cycle of threads, a thread can only call the start () method once, and it is illegal to start a thread multiple times. This is especially the time when the thread has finished executing and cannot be restarted.

Third, run () method

1. What is the method of the Run method? What is the Run method associated with the Start method?

The run () method is called as a normal method
Run () is a common method, except that when the thread calls the start () method, the thread will call the run () method once the thread has been dispatched by the CPU and is in a running state.

2. Execution of the run () method does not require the thread to call the start () method

As stated above, the run () method is a normal object method, so it is not necessary for the thread to call Start () before it can be called. A thread object 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();

The above output is fixed:

Value of Count: 1
Value of Count: 2

Look at another example:

 Thread t1 = new Thread(new MyTask()); Thread t2 = new Thread(new MyTask());     t1.start();     t2.start();

The result of this output is not fixed because the thread is unpredictable to run. The results may not be the same.

MyTask class:

//实现Runnable接口class MyTask implements Runnable{    int count;    public MyTask(int count) {        this.count=count;    }    @Override    public void run() {        System.out.println("count的值:"+count);    }}
Example2:

1. Start the thread with the Start method

  public class Main {public static void main (string[] args) {thread T1 = new Thread (n              EW 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);              Simulation time-consuming task}} catch (Interruptedexception e) {e.printstacktrace ();                  }}} class T2 implements Runnable {public void run () {try {                      for (int i=0;i>-10;i--) {System.out.println (i);  Thread.Sleep (100);              Simulation time-consuming task}} catch (Interruptedexception e) {e.printstacktrace (); }          }      }  

Results:

Illustrates that two threads are executed concurrently.

2. Start the thread with the Run method first
Change the above start () to 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();          }      }  


Illustrates that two threads are actually executed sequentially.

Summarize:

Through instance 1 and the instance and we can know that the Start method is used to start the thread, can implement concurrency, and the Run method is only a common method, is not implemented concurrently, but is called when concurrent execution.

Speaking of this, do not know the small partners do not understand the difference between the two methods, if there are doubts, you can message exchange.

Iv. start () method and run () method source code parsing (based on jdk1.7.0_40)
    public synchronized void start() {          // 如果线程不是"就绪状态",则抛出异常!          if (threadStatus != 0)              throw new IllegalThreadStateException();          // 将线程添加到ThreadGroup中          group.add(this);          boolean started = false;          try {              // 通过start0()启动线程,新线程会调用run()方法              start0();              // 设置started标记=true              started = true;          } finally {              try {                  if (!started) {                      group.threadStartFailed(this);                  }              } catch (Throwable ignore) {              }          }      }  
public void run() {      if (target != null) {          target.run();      }  
Five, really understand the thread class

The object of the thread class is actually a Java object, except that the object of each thread class corresponds to a thread. The object of the thread class is the information that is provided to the user to manipulate the thread and get the thread . The real bottom thread user is invisible.
Therefore, when a thread ends and dies, the corresponding thread object can still be called, except for all methods (the Start () method) (the dead thread cannot start again), such as Run (), GetName (), getpriority () , and so on.

//简单起见,使用匿名内部类的方法来创建线程    Thread thread = new Thread(){        @Override        public void run() {            System.out.println("Thread对象的run方法被执行了");        }    };    //线程启动    thread.start();    //用循环去监听线程thread是否还活着,只有当线程thread已经结束了,才跳出循环    while(thread.isAlive()){}    //线程thread结束了,但仍能调用thread对象的大部分方法    System.out.println("线程"+thread.getName()+"的状态:"+thread.getState()+"---优先级:"+thread.getPriority());    //调用run方法    thread.run();    //当线程结束时,start方法不能调用,下面的方法将会抛出异常    thread.start();
Resources
    • Http://www.cnblogs.com/jinggod/p/8485143.html
    • 47911181
    • 7685076

The article is inappropriate, please correct me, you can also pay attention to my public number: 好好学java , access to high-quality learning resources.

The start () method and the Run () method of the threading thread class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.