primers

I’ve been interviewing a lot of Java engineers recently, and I’d like to share some of my experiences with you. For example, one of my young men was “sent away” by me last time. I’ll try to reconstruct the interview scene as follows:

The JDK Thread class has two methods called start() and run(). Do you know the difference between them?

Brother: Err…… Seems to be running… Run a thread……

I: that is to run a thread, the design of a method is good, there is no need for two methods?

Brother: This…… Not sure……

Me: Ok, let’s call it a day… (get up)

[PS: Of course, this last stand is the result of having already asked several questions.]

Analysis of the

As we all know, Java interviews usually involve multiple threads. I usually start with simple questions and follow up if the answers are good. After a few simple questions, I have a basic sense of how well I know the candidate.

If a candidate can’t answer even the simplest of questions, it shows me that either his or her foundation is poor or that I haven’t paid enough attention to preparing for the interview. No matter what the reason, in the mind of the interviewer, the result is predictable.

The principle of

What’s the difference between start() and run() in Thread?

Before we look at the Thread methods, let’s take a look at the Thread states. This will help us understand the methods in the Thread class.

  • Create (new) state: A multithreaded object is ready
  • Runnable state: The start() method is called, waiting for the CPU to schedule
  • Running state: Execute the run() method
  • Blocked: Execution is temporarily halted, possibly freeing resources for use by other threads
  • Dead state: Thread destruction

There are two ways to implement and start a thread, which we know by heart:

  • Write a class that inherits from Thread and overrides the run() method. Start the thread with the start() method
  • Write a class that implements the Runnable interface and implements the run() method. Start the Thread with the new Thread(Runnable target).start() method

To tell the difference between a start() method call and a run() method call, look at the following example:

package cn.java.basic;

/ * * *@author Jessehuang
 */
public class Test {
    public static void main(String[] args) {
        System.out.println("Main thread ID:" + Thread.currentThread().getId());
        MyThread thread1 = new MyThread("thread1");
        thread1.start();
        MyThread thread2 = new MyThread("thread2"); thread2.run(); }}class MyThread extends Thread {
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run(a) {
        System.out.println("name:" + name + "Child thread ID:+ Thread.currentThread().getId()); }}Copy the code

Running results:

ID:1 Name :thread2 subthread ID:1 Name :thread1 subthread ID:10Copy the code

The following conclusions can be drawn from the output results:

Thread1 and thread2 have the same ID. Thread2 and thread2 have the same ID. This means that a run() call does not create a new thread, but runs the run() method directly on the main thread.

Thread1’s run() method is called before thread2’s run() method, but the run() method of thread2 is called first.

Start () and run(); The start() method calls the native start0(), and run() is simply run() that overrides the Runnable Thread implementation. Relatively simple, will not paste, can be consulted in the JDK.

OK, let’s break it down into a more formal (but slightly dry) text to illustrate the difference between the two:

1. Start () method

It starts a new thread.

Once it gets the CPU time slice, it will start executing the corresponding thread’s run() method. The run() method is called the thread body. It contains the contents of the thread to be executed. The thread terminates when the run() method finishes running.

Using the start() method to start the thread, the true implementation of multi-threaded running, that is, without waiting for a thread’s run method body code to complete the execution can directly continue to execute the following code, that is, thread switch.

2. Run () method

It’s just a normal member method, it doesn’t matter, you can call it again and again, it’s not going to help you start a new thread anyway.

There is only one thread in the program, the main thread, so there is only one path of execution, from top to bottom, which results in waiting for the body of the run method to complete before continuing with the following code. That is, multithreading is not implemented.

How does ** understand the concept of “multithreading” **?

For example, it’s summer vacation, and a bunch of kids come to your house and they want to play your PSP, but you only have one PSP, and you tell them to line up and play next to each other so that everyone can play. The PSP is the CPU, and queuing is the start() method in the thread. When the CPU selects a child, it runs () and starts playing the game. When the CPU runs out of time, the thread continues queuing, waiting for the next run().

Multithread uses CPU namely namely time sharing actually, let all threads execute together on macroscopically, little imagine, it is CPU is doing extremely fast context switch, build a kind of dazzling illusion to you, still really think to be executed at the same time.

conclusion

Well, although we “sent away” the little brother at the beginning of the article, but as a kind person, or to help him summarize the answer:

  1. Start () can start a new thread, run() cannot
  2. Start () cannot be called repeatedly, run() can
  3. The run code in start() can continue executing the code below without completing execution, making a thread switch, while the run() method must wait for its code to complete before it can continue executing the code below
  4. Start () implements multithreading; run() does not