Java interview questions, analyzing multithreading behavior from the bottom of Java

Original: enjoy learning classroom lecturer
Reprint, please state the source!

For example, frameworks that handle large amounts of information, such as Spring batch processing, use threads to manage data. Operating threads or CPU processes at the same time can improve performance, resulting in faster and more efficient programs.

We can call. Thread() Getname() method to access the executing thread, as shown below:

public class MainThread {

    public static void main(String[]args) {
       System.out.println(Thread.currentThread().getName());
    }

}

This code will print "main" to identify the thread currently executing. This is the first step in learning the concept of multithreading.

The thread life cycle of Java includes six thread states:

  • New: Thread() has instantiated a new.

  • Runnable connection: the start() method of this Thread is called.

  • Running: start() has called the method and the thread is running.

  • Suspended: the thread is temporarily suspended and can be resumed by another thread.

  • Blocked: the thread is waiting for an opportunity to run. This happens when one thread has called the synchronized() method and the next thread must wait until it completes.

  • Terminated: the execution of the thread is completed.

Concurrent multithreading: extending the Thread class

The simplest way is to complete concurrent processing by extending the Thread class, as shown below:

public class InheritingThread extends Thread {

    InheritingThread(StringthreadName) {
        super(threadName);
    }

    public static voidmain(String... inheriting) {
       System.out.println(Thread.currentThread().getName() + " isrunning");

        newInheritingThread("inheritingThread").start();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+ " is running");
    }
}

When we call the method with start() using new, inheritingThread() will run() to execute the logic in the method.

We also pass the name of the second Thread in the Thread class constructor, so the output will be:

main is running.
inheritingThread is running.

Concurrent multithreading: Runnable interface

Passing Runnable inside the Thread constructor results in less coupling and greater flexibility. After the Runnable is passed, we can call the method with start() as in the previous example:

public class RunnableThread implements Runnable {

    public static voidmain(String... runnableThread) {
       System.out.println(Thread.currentThread().getName());

        new Thread(new RunnableThread()).start();
    }

    @Override
    public void run() {
       System.out.println(Thread.currentThread().getName());
    }

Non daemon vs daemon thread

In terms of execution, there are two types of threads:

  • Non daemon threads are executed until the end. The main thread itself is a good example of a non daemon thread. main() unless system Exit() forces the program to complete, otherwise the code input will always be executed to the end.

  • A daemon thread, on the contrary, is a handler that does not need to be executed until the end.

Remember the rule: if a closed non daemon thread ends before the daemon thread, the daemon thread will execute before it ends. To better understand the relationship between daemon and non daemon threads, please refer to the following examples:

import java.util.stream.IntStream;

public class NonDaemonAndDaemonThread {

    public static voidmain(String... nonDaemonAndDaemon) throws                        InterruptedException {
       System.out.println("Starting the execution in the Thread "+      Thread.currentThread().getName());

        Thread daemonThread = newThread(() ->     IntStream.rangeClosed(1, 100000)
               .forEach(System.out::println));

       daemonThread.setDaemon(true);
        daemonThread.start();

        Thread.sleep(10);

        System.out.println("Endof the execution in the Thread " +   
                                          Thread.currentThread().getName());
    }

}

In this example, I use daemon threads to declare a range of 1 to 100000, iterate over all this, and then print.

The output will proceed as follows:

1. Start execution in the main thread.

2. Print numbers from 1 to 100000.

3. The execution in the main thread ends, which is likely to be completed before the iteration reaches 100000.

The final output will depend on your JVM implementation.

Thread priority and JVM

You can use this setPriority method to determine the priority of thread execution, but how it is handled depends on the JVM implementation. Linux, MacOS and Windows all have different JVM implementations, and each will handle thread priority according to its own default value.

However, the Thread priority you set does affect the order of Thread calls. The three constants on the Thread class are:

 /**
    * The minimum priority that athread can have.
     */
    public static final intMIN_PRIORITY = 1;

   /**
     * The default priority that isassigned to a thread.
     */
    public static final intNORM_PRIORITY = 5;

    /**
     * The maximum priority that athread can have.
     */
    public static final intMAX_PRIORITY = 10;

Try running some tests on the following code to see the final execution priority

public class ThreadPriority {

    public static voidmain(String... threadPriority) {
        Thread moeThread = newThread(() -> System.out.println("Moe"));
        Thread barneyThread = newThread(() -> System.out.println("Barney"));
        Thread homerThread = newThread(() -> System.out.println("Homer"));

       moeThread.setPriority(Thread.MAX_PRIORITY);
       barneyThread.setPriority(Thread.NORM_PRIORITY);
       homerThread.setPriority(Thread.MIN_PRIORITY);

        homerThread.start();
        barneyThread.start();
        moeThread.start();
    }
}

Even if we set moeThread to MAX_PRIORITY, we can't expect to execute this thread first. Instead, the order of execution will be random.

However, there is a problem with using constants: if the priority number passed is not in the range of 1 to 10, the setPriority () method will throw an IllegalArgumentException. So we can use enumeration to solve this problem. Enumerating Enums not only simplifies the code, but also can better control the execution of the code.

public class ThreadChallenge {
    private static int line = 10;

    public static voidmain(String... doYourBest) {
        newtool("Car").start();

        tool Bike = newtool("Bike");
       Bike.setPriority(Thread.MAX_PRIORITY);
        Bike.setDaemon(false);
        Bike.start();

        tool Train = newtool("Train");
       Train.setPriority(Thread.MIN_PRIORITY);
        Train.start();
    }

    static class tool extends Thread{
        tool(String Name) {super(Name); }

        @Override public void run(){
            line++;
            if (line == 13) {
               System.out.println(this.getName());
            }
        }
    }
}

In the above code, we created three threads:

The first thread is Car, for which we have assigned a default priority.

The second thread is Bike, which is assigned MAX_PRIORITY priority.

The third thread is Train, and min is allocated_ Priority priority.

Then we started multithreading. To determine the order in which threads will run, you may first notice that the tool class extends the Thread class, and we have passed the Thread name in the constructor.

We also print if line equals 13 in run().

be careful! Even if Train is the third thread in our execution sequence and MIN_PRIORITY cannot guarantee that it will be executed at the end of all JVM implementations.

You may also notice that in this example, we set the Bike thread as a daemon, so it is a daemon thread, and Bike may never complete execution. However, the other two threads are non daemons by default, so the Car and Train threads will certainly complete their execution.

In short, the result will be D: uncertain, because there is no guarantee that the thread scheduler will follow our execution order or thread priority. Keep in mind that without the tools of JUC, we cannot rely on program logic (thread or thread priority order) to predict the execution order of threads.

Common multithreading errors

  • Call the run() method to try to start a new thread.

  • Attempt to start a thread twice (this will result in an IllegalThreadStateException).

  • Allows multiple processes to change the state of an object when it should not be changed.

  • Write program logic that depends on thread priority

  • Depends on the order of thread execution - even if we start a thread first, there is no guarantee that it will be executed first.

What to remember about multithreading

  • Call the start() method to start a Thread.

  • You can extend the class Thread directly to use threads.

  • Thread actions can be implemented in the Runnable interface.

  • Thread priority depends on the JVM implementation.

  • Thread behavior will always depend on the JVM implementation.

  • If a closed non daemon thread ends first, the daemon thread cannot complete.

Today's benefits (click the text hyperlink below to get it)




If you encounter a bottleneck in technology improvement, or lack advanced Android video learning to improve yourself, there are a large number of large factory interview questions to prepare for your interview!

last

Even job hopping is a learning process. Only a comprehensive review can make us better enrich ourselves, arm ourselves and make our interview no longer rough! Today, I'll share with you a comprehensive collection of Java interview questions on Github, which helped me win the Offer of a large factory and raise my monthly salary to 30K!

Data collection method: Blue portal

I also share it with you for the first time. I hope I can help you go to the big factory you like! Prepare for gold, silver and four!
There are 20 topics of knowledge points in total, which are:

Dubbo interview topic

JVM interview topics

Java Concurrent interview topic

Kafka interview topic

MongDB interview topic

MyBatis interview topic

MySQL interview topic

Netty interview topic

RabbitMQ interview topic

Redis interview topic

Spring Cloud interview topic

SpringBoot interview topic

zookeeper interview topic

Summary of common interview algorithm questions

Basic topics of computer network

Special topics on Design Patterns


Cloud interview topic**

[external chain picture transferring... (img-DfZFXdNt-1623727660042)]

SpringBoot interview topic

[external chain picture transferring... (img-03LiU1iN-1623727660043)]

zookeeper interview topic

[external chain picture transferring... (IMG tsgnrdlr-1623727660044)]

Summary of common interview algorithm questions

[external chain picture transferring... (img-J1Uyod5M-1623727660045)]

Basic topics of computer network

[external chain picture transferring... (img-rS4Wsv9s-1623727660045)]

Special topics on Design Patterns

[external chain picture transferring... (IMG rhhegydh-1623727660046)]

Keywords: Java Interview Programmer

Added by luvburn on Sun, 30 Jan 2022 11:21:14 +0200