Did the Java interview fail? Have you read this article? ——Common interview questions for the latest version of Java in 2020 (3)

Preface

These interview questions are the latest version of 2020. Some of the most common questions related to Java, don’t panic after reading these interviews. Some answers are summed up by myself, and some answers are collected and organized on the Internet. For your reference only. If you find a mistake, I hope you can forgive me, and I would like to let you know, thank you~

Insert picture description here

24. What is the difference between parallel and concurrent?

  • Parallel means that two or more events occur at the same time; concurrency means that two or more events occur at the same time interval.
  • Concurrency is multiple events on different entities, and concurrency is multiple events on the same entity.
  • Process multiple tasks "simultaneously" on one processor, and process multiple tasks on multiple processors at the same time. Such as hadoop distributed cluster.

Therefore, the goal of concurrent programming is to make full use of each core of the processor to achieve the highest processing performance.

25. The difference between thread and process?

In short, a process is the basic unit of program operation and resource allocation. A program has at least one process, and a process has at least one thread. The process has an independent memory unit during execution, and multiple threads share memory resources, reducing the number of switching times, and thus higher efficiency. A thread is an entity of a process, the basic unit of cpu scheduling and dispatch, and a basic unit that is smaller than a program and can run independently. Multiple threads in the same process can execute concurrently.

26. What is a daemon thread?

The daemon thread (that is, daemon thread) is a service thread, to be precise, it serves other threads.

27. What are the ways to create threads?

①. Inherit the Thread class to create a thread class

  • Define a subclass of the Thread class and override the run method of this class. The method body of the run method represents the task to be completed by the thread. Therefore, the run() method is called the execution body.
  • Create an instance of the Thread subclass, that is, create a thread object.
  • Call the start() method of the thread object to start the thread.

②. Create thread class through Runnable interface

  • Define the implementation class of the runnable interface and rewrite the run() method of the interface. The method body of the run() method is also the thread execution body of the thread.
  • Create an instance of the Runnable implementation class, and use this instance as the target of Thread to create a Thread object, which is the real thread object.
  • Call the start() method of the thread object to start the thread.

③. Create thread through Callable and Future

  • Create an implementation class of the Callable interface and implement the call() method. The call() method will act as the thread execution body and have a return value.
  • Create an instance of the Callable implementation class, and use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call() method of the Callable object.
  • Use the FutureTask object as the target of the Thread object to create and start a new thread.
  • Call the get() method of the FutureTask object to obtain the return value after the execution of the child thread ends.

28. What is the difference between runnable and callable?

There is a bit of a deep question, and I also see the breadth of knowledge of a Java programmer.

  • The return value of the run() method in the Runnable interface is void. What it does is purely execute the code in the run() method;
  • The call() method in the Callable interface has a return value and is a generic type. It can be used with Future and FutureTask to obtain the result of asynchronous execution.

29. What are the statuses of threads?

A thread usually has five states, created, ready, running, blocked, and dead.

  • Create status. When the thread object is generated, the start method of the object is not called. This is the thread being created.
  • Ready state. When the start method of the thread object is called, the thread enters the ready state, but at this time the thread scheduler has not set the thread as the current thread, and is now in the ready state. After the thread runs and comes back from waiting or sleeping, it will also be in the ready state.
  • Operating status. The thread scheduler sets the thread in the ready state as the current thread. At this time, the thread enters the running state and starts to run the code in the run function.
  • Blocked state. When a thread is running, it is suspended, usually to wait for a certain time to happen (for example, a certain resource is ready) before continuing. Methods such as sleep, suspend, wait can cause thread blocking.
  • State of death. If the run method of a thread ends or the stop method is called, the thread will die. For threads that have died, they can no longer use the start method to make them ready

30. What is the difference between sleep() and wait()?

  • sleep(): The method is a static method of the thread class (Thread), which allows the calling thread to enter the sleep state and gives up execution opportunities to other threads. After the sleep time is over, the thread enters the ready state and competes with other threads for the execution time of the cpu. Because sleep()
    is a static method, it cannot change the machine lock of the object. When the sleep()
    method is called in a synchronized block , although the thread goes to sleep, the machine lock of the object is not released, and other threads still cannot access this Object.
  • wait(): wait() is a method of the Object class. When a thread executes to the wait method, it enters a waiting pool related to the object, and releases the machine lock of the object at the same time, so that other threads can access it. notify, notifyAll methods to wake up waiting threads

31. What is the difference between notify() and notifyAll()?

  • If the thread calls the wait() method of the object, the thread will be in the waiting pool of the object, and the threads in the waiting pool will not compete for the object's lock.
  • When a thread calls the object's notifyAll() method (wake up all wait threads) or notify() method (only a random wait
    thread is awakened), the awakened thread will enter the object's lock pool, and the lock pool The thread will compete for the object lock. In other words, after calling notify, as long as one thread enters the lock pool from the waiting pool, notifyAll will move all threads in the waiting pool of the object to the lock pool, waiting for lock competition.
  • The high-priority thread has a high probability of competing for the object lock. If a thread does not compete for the object lock, it will remain in the lock pool. Only if the thread calls the wait() method again, it will return to the waiting pool. in. The thread that competes for the object lock will continue to execute until the synchronized code block is executed, it will release the object lock, and then the threads in the lock pool will continue to compete for the object lock.

32. What is the difference between thread run() and start()?

Each thread completes its operation through the method run() corresponding to a specific Thread object. The method run() is called the thread body. Start a thread by calling the start() method of the Thread class.

The start() method starts a thread, which truly realizes multithreaded operation. At this time, there is no need to wait for the execution of the run method body code to complete, you can directly continue to execute the following code; at this time, the thread is in a ready state and is not running. Then the method run() is called through the Thread class to complete its running state, where the method run() is called the thread body, which contains the content of the thread to be executed, the Run method ends, and the thread terminates. Then the CPU schedules other threads.

The run() method is in this thread, it's just a function in the thread, not multithreaded. If you call run() directly, it is actually equivalent to calling an ordinary function. The run() method must wait for the run() method to complete before executing the following code, so there is still only one execution path, and there is no thread at all. Therefore, the start() method should be used instead of the run() method in multi-threaded execution.

33. What are the ways to create a thread pool?

①. newFixedThreadPool(int nThreads)

Create a fixed-length thread pool. Whenever a task is submitted, a thread is created until the maximum number of thread pool is reached. At this time, the thread size will no longer change. When the thread ends with an unexpected error, the thread pool will supplement A new thread.

②. newCachedThreadPool()

Create a cacheable thread pool. If the size of the thread pool exceeds the processing demand, idle threads will be automatically recycled, and when the demand increases, new threads can be automatically added. There is no limit to the size of the thread pool.

③. newSingleThreadExecutor ()

This is a single-threaded Executor. It creates a single worker thread to execute tasks. If this thread ends abnormally, a new one will be created to replace it; its characteristic is to ensure that the tasks are executed serially in the order of the queue.

④. newScheduledThreadPool(int corePoolSize)

A fixed-length thread pool is created, and tasks are executed in a delayed or timed manner, similar to Timer.

34. What is the difference between the submit() and execute() methods in the thread pool?

The received parameters are different

  • Submit has a return value, but execute does not
  • Submit to facilitate Exception handling

35. How to ensure the safe operation of multiple threads in java programs?

Thread safety is reflected in three aspects:

  • Atomicity: provide mutually exclusive access, only one thread can operate on data at the same time (atomic, synchronized);
  • Visibility: A thread's modification of the main memory can be seen by other threads in time (synchronized, volatile);
  • Orderliness: One thread observes the execution order of instructions in other threads. Due to instruction reordering, the observation results are generally disorderly (happens-before principle).

36. What is a deadlock?

Deadlock refers to a phenomenon in which two or more processes are blocked due to competition for resources or due to communication with each other during the execution. If there is no external force, they will not be able to advance. At this time, the system is said to be in a deadlock state or the system has a deadlock. These processes that are always waiting for each other are called deadlock processes. It is an error at the operating system level. It is the abbreviation for process deadlock. It was first proposed by Dijkstra in 1965 when studying the banker algorithm. It is one of the most difficult problems in the computer operating system and even the entire concurrent programming field.

37. How to prevent deadlock?

Four necessary conditions for deadlock:

  • Mutually exclusive conditions: The process does not allow other processes to access the allocated resources. If other processes access the resource, they can only wait until the process that occupies the resource is used to release the resource.
  • Request and hold conditions: After the process obtains a certain resource, it sends a request to other resources, but the resource may be occupied by other processes. This request is blocked, but it keeps holding on to the resources it has obtained
  • Inalienable conditions: refers to the resources that the process has acquired. They cannot be deprived before they are used. They can only be released by themselves after they are used.
  • Loop waiting condition: refers to the formation of a head-to-tail loop waiting resource relationship between several processes after a deadlock occurs.

These four conditions are necessary conditions for deadlock. As long as the system is deadlocked, these conditions must be established, and as long as one of the above conditions is not met, deadlock will not occur.

Understanding the causes of deadlocks, especially the four necessary conditions for deadlocks, can avoid, prevent and remove deadlocks to the greatest possible extent.

Therefore, in system design, process scheduling, etc., pay attention to how to prevent these four necessary conditions from being established, and how to determine a reasonable resource allocation algorithm to prevent processes from occupying system resources permanently.

In addition, prevent the process from occupying resources while in a waiting state. Therefore, reasonable planning should be given to the allocation of resources.

38. What is ThreadLocal? What are the usage scenarios?

Thread local variables are variables confined to the inside of the thread, belong to the thread itself, and are not shared among multiple threads. Java provides ThreadLocal class to support thread local variables, which is a way to achieve thread safety. But be careful when using thread-local variables in a management environment (such as a web server). In this case, the life cycle of a worker thread is longer than the life cycle of any application variable. Once any thread-local variables are not released after the work is completed, there is a risk of memory leaks in Java applications.

39. Tell me about the underlying implementation principle of synchronized?

Synchronized can ensure that only one method can enter the critical section at the same time when the method or code block is running, and it can also ensure the memory visibility of shared variables.

Every object in Java can be used as a lock, which is the basis for synchronized to achieve synchronization:

  • Ordinary synchronization method, the lock is the current instance object
  • Static synchronization method, the lock is the class object of the current class
  • Synchronization method block, the lock is the object inside the brackets

40. What is the difference between synchronized and volatile?

  • Volatile essentially tells the jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from the main memory;
    synchronized is to lock the current variable, only the current thread can access the variable, other threads are blocked .
  • Volatile can only be used at the variable level; synchronized can be used at the variable, method, and class level.
  • Volatile can only achieve the visibility of the modification of variables, and cannot guarantee the atomicity; while synchronized can ensure the visibility and atomicity of the modification of variables.
  • Volatile does not cause thread blocking; synchronized may cause thread blocking.
  • Variables marked with volatile will not be optimized by the compiler; variables marked with synchronized can be optimized by the compiler.

41. What is the difference between synchronized and Lock?

  • First, synchronized is a built-in keyword in java. At the jvm level, Lock is a java class;
  • Synchronized cannot determine whether to acquire the lock status, Lock can determine whether to acquire the lock;
  • Synchronized will automatically release the lock (a thread will release the lock after executing the synchronization code; b
    thread will release the lock if an exception occurs during the execution of the thread), the Lock must be manually released in the finally (unlock() method releases the lock), otherwise it will easily cause the thread to die lock;
  • Two threads 1 and 2 with the synchronized keyword, if the current thread 1 obtains the lock, the thread 2 waits. If thread 1 is blocked, thread 2 will wait forever, and the Lock lock will not necessarily wait forever. If the lock cannot be acquired, the thread can end without waiting;
  • Synchronized locks can be reentrant, uninterruptible, and unfair, while Lock locks can be reentrant, judged, and fair (both are acceptable);
  • Lock locks are suitable for synchronization problems with a large number of synchronized codes, and synchronized locks are suitable for synchronization problems with a small amount of codes.

42. What is the difference between synchronized and ReentrantLock?

Synchronized is the same keyword as if, else, for, while, and ReentrantLock is a class, which is the essential difference between the two. Since ReentrantLock is a class, it provides more and more flexible features than synchronized. It can be inherited, can have methods, and can have a variety of class variables. ReentrantLock is more extensible than synchronized in several aspects:

  • ReentrantLock can set the waiting time to acquire the lock, so as to avoid deadlock
  • ReentrantLock can obtain information about various locks
  • ReentrantLock can flexibly implement multiple notifications

In addition, the lock mechanism of the two is actually different: the bottom layer of ReentrantLock calls the Unsafe park method to lock, and the synchronized operation should be the mark word in the object header.

43. Tell me about the principle of atomic?

The basic feature of the classes in the Atomic package is that in a multithreaded environment, when multiple threads operate on a single variable (including basic types and reference types) at the same time, it is exclusive, that is, when multiple threads simultaneously value the variable When updating, only one thread can succeed, and the unsuccessful thread can continue to try like a spin lock and wait until the execution succeeds.

The core methods in the Atomic series of classes will call several local methods in the unsafe class. One thing we need to know is the Unsafe class, its full name is: sun.misc.Unsafe, this class contains a large number of operations on C code, including many direct memory allocation and atomic operation calls, and the reason why it is marked as non The safe thing is to tell you that a large number of method calls in this will have safety hazards and need to be used carefully, otherwise it will cause serious consequences. For example, when allocating memory through unsafe, if you specify certain areas yourself, it may cause something similar to C++ The pointer is out of bounds to other processes.

Guess you like

Origin blog.csdn.net/weixin_50333534/article/details/108673104