This is the second day of my participation in Gwen Challenge

Author: Flower brother

Wechat official account: Programming brother Hua

preface

One day early in the morning (9:00), pack force bound two leaders to the company early.

Dog: Longgie, do you want to squat in the hole? Take a good seat while no one else is around. Then I’ll show you a good baby.

I: smelly shameless, early in the morning thinking squat pit water, I flat is how education you, can learn from me.

Me: really sweet…..

Dog leftover son: Flower Gie, I heard that a kid from the next group quit his job and entered that company named Ah. It’s so annoying.

I: you return don’t unconvinced spirit, somebody else belly inside really have goods, don’t believe me to ask you a few questions, see you ability answer come up?

The body of the

Me: Have you ever used multithreading? How many ways can you create a thread?

Threads can be created in two typical ways: implementing the Runnable interface and inheriting the Thread class. Threads can also be created through Thread pools, timers, anonymous inner classes, etc.

Me: Anything else?

Heart whisper: this shit words ask of want to set me. Ah.. The.. There is.

Although there are so many ways to create a Thread, but we can look at the source code, in fact, there is only one way, that is to create a Thread by creating a new Thread class, and finally through the start method to create a new Thread, but there are two implementations of the run method.

  • The first way to inherit Thread is to override the run method of the parent class
  • The second way to implement Runnable is to implement the interface’s Run method and pass the Runnable instance to the Thread class.

1) Create the Thread class and implement the run method

// The implementation
class ThreadTest extends Thread{
    @Override
    public void run(a) {
        System.out.println("I love Jay.");
    }
}
 Thread thread = new Thread(new ThreadTest());
 thread.start();

// The thread finally calls target.run()
private Runnable target;
@Override
    public void run(a) {
        if(target ! =null) { target.run(); }}Copy the code

2) Implement Runnable, run method implementation

Thread thread = new Thread(new Runnable() {
    @Override
    public void run(a) {
        System.out.println("Hello, everybody. I call the dog Shengzi."); }}); thread.start();Copy the code

As for the thread pool, timer and other tools are essentially a kind of implementation of the above.

Do you know whether it is better to inherit Thread or implement the Runnable interface?

Implementing the Runnable interface is better for several main reasons:

  • Java is single-inheritance, which limits extensibility if Thread is inherited.
  • Implementing the Runnable interface decouples concrete tasks (the run method) and creation threads (the Thread class) by allowing the same task class to be passed to different threads. The task class is not responsible for creating threads, etc.
  • Each time a new task is created, only one new Thread can be created. Even if the task only prints a line of logs, the creation and destruction of the Thread must be completed, resulting in a serious waste of resources. Runnable and thread pools avoid this waste.

What states do you know about threads? What is its life cycle?

Florgie, if you stick your hand in here, I’ll show you one thing and you’ll understand.

This what, you step a horse…. !

Excuse me… Wrong. Got my breakfast bun out. Here it is… Is this

This graph is the best I’ve ever drawn, and we can see that Java threads have a total of six life cycles.

  • New: Creates a thread object.

    1. The JVM allocates memory for it and initializes the values of its member variables;
    2. Threads are not scheduled in this state.
  • Ready state (Runnable) : When the thread object calls the start method, it enters the ready state. Note that the thread will still be in the Runnable state after it retrieves the time slice.

    1. The JVM creates method call stacks and program counters;
    2. The thread in this state is always in a thread-ready queue (although in the form of a queue, in fact, make it a runnable pool rather than a runnable queue. Because CPU scheduling is not necessarily in first-in, first-out order), threads are not running;
    3. Threads do not execute the start() method immediately and wait for the system to allocate CPU time slices for them.
  • Blocked: A thread attempts to acquire a synchronized method/block, but the monitor lock is occupied by another thread; A running thread, under certain circumstances, cedes its CPU execution and enters a blocking state.

  • TIMED_WAITING: threads call sleep and enter sleep. After a certain time, they will wake up automatically. When sleep is over, they will enter the ready state waiting for CPU execution.

  • WAITING: a thread invoking the wait method that holds the lock. A thread in this state is not allocated CPU. It must wait for notify to wake it up, or it will wait indefinitely.

  • Terminated: The thread is Terminated or an exception is thrown and thread resources are Terminated.

    There are three ways for a thread to enter the dead state:

    1. The run() or call() method completes, and the thread terminates normally;
    2. The thread throws an uncaught exception;
    3. Call the thread’s stop() method directly — not recommended because it can cause deadlocks.

    Java threads do not have Running states. Their Runnable contains the ready and Running states in the operating system.

The thread that calls start() ends up calling run().

So why don’t we just call the run() method?

Since start() is used to start the thread, the run() method is simply the code that executes the thread’s runtime. If run() is called directly, it is just a normal method that is called, regardless of the thread’s life cycle. Also, we need to note that the second call to start() method will raise a runtime exception.

Do you know the difference between sleep and wait/notify?

Well, that’s not gonna get us either.

  • The same:

    1. They can both block the thread.
    2. They can all respond to thread.interrupt.
  • The difference between

    1. Sleep () comes from Thread, and wait() from Object.
    2. Sleep () does not release the monitor lock, but wait() does.
    3. The sleep() time is automatically restored, and wait() can be awakened directly using notify()/notifyAll().
    4. Wait methods need to be executed in synchronous methods, while sleep does not.

Do you know the difference between yeid and sleep?

Hey, I’m glad I was prepared. Yield is used to yield time slices, so the thread is still Runnable, so it can still be scheduled again, and the sleep will block, so it won’t be called by the thread scheduler during the waiting time.

The answer is also ok, almost catch up with me, there is a question, daemon thread and ordinary thread difference do you understand?

Hold grass, lunch time arrived, did not say with you, today temporarily arrive here, such as na supplement nutrition, tomorrow will meet you again.

conclusion

The above is today’s introduction of multithreading basic knowledge, this knowledge point is more, here spend Gie will be divided into a number of pages to introduce, I dare to assure the dog remaining son, as long as you seriously with good spend Gie this series, the interview will be able to small abuse the interviewer, if not… I’ll give you the rest of my dog.

Great oaks from little acorns grow. Gie believed that only by laying a solid foundation and practicing his internal skills seriously, could he walk more easily and farther.

Pay attention to avoid getting lost

The above is the whole content of this issue, if there is any mistake, please leave a message for advice, thank you very much. I’m GieGie, feel free to leave a comment and we’ll see you next time at 🦮.

The article continues to update, you can search the wechat “flower brother programming” for the first time to read, the follow-up will continue to update Java interview and all kinds of knowledge points, interested partners welcome to pay attention to, learn together, together hah 🐮🥃:

Original is not easy, how can you bear to whoring for nothing, if you think this article is a little useful to you, thank old tie for this article to like, comment or forward, because this will be my output more quality articles of power, thank you!