preface

Now whether it is a large company or a small company, to interview will be asked about multi-threading and concurrent programming knowledge, we interview this knowledge must be prepared in advance.

Java Oop, Java Collections containers, Java exceptions, concurrent programming, Java reflection, Java serialization, JVM, Redis, Spring MVC, MyBatis, MySQL database, messaging middleware MQ, Dubbo, Linux, ZooKeeper, distributed & data structure and algorithm, etc. 25 thematic technical points, are all small editor in each big factory summary of the interview real questions, there have been many fans with this PDF to win many big factory offer. Today, here is a summary to share to everyone! [Finished]

The full version of the Java interview questions address: 2021 latest interview questions collection collection.

The serial number project content link
1 The middleware Java Middleware (2021) Juejin. Cn/post / 694870…
2 Micro service Java Microservices (2021) Juejin. Cn/post / 694906…
3 Concurrent programming Concurrent Programming in Java (2021 latest Edition) Juejin. Cn/post / 695053…
4 Java based Java Basics (2021) Juejin. Cn/post / 695062…
5 Spring Boot Spring Boot Interview Questions (2021 Latest edition) Juejin. Cn/post / 695137…
6 Redis Redis Interview Questions (2021 Latest edition) Juejin. Cn/post / 695166…
7 Spring MVC Spring MVC (2021) Juejin. Cn/post / 695166…
8 Spring Cloud Spring Cloud Interview Questions (2021) Juejin. Cn/post / 695245…
9 MySQL optimization MySQL optimize interview questions (2021 latest edition) Juejin. Cn/post / 695246…
10 JVM JVM Performance Tuning Interview questions (2021 Latest Edition) Juejin. Cn/post / 695246…
11 Linux Linux Interview Questions (2021 latest edition) Juejin. Cn/post / 695287…
12 Mybatis Mybatis (2021 latest Edition) Juejin. Cn/post / 695287…
13 Network programming TCP, UDP, Socket, Http Network programming interview (2021 latest edition) Juejin. Cn/post / 695287…
14 Design patterns Design Mode Interview Questions (2021 Latest edition) Juejin. Cn/post / 695544…
15 Big data 100 Big Data Interview Questions (2021 latest edition) Juejin. Cn/post / 695544…
16 Tomcat Tomcat Interview Questions (2021 Latest edition) Juejin. Cn/post / 695570…
17 multithreading Multithreaded Interview Questions (2021 Latest edition) Juejin. Cn/editor/draf…
18 Nginx Nginx_BIO_NIO_AIO interview Questions (2021 Latest edition) Juejin. Cn/editor/draf…
19 memcache Memcache Interview Questions (2021 latest edition) Juejin. Cn/post / 695608…
20 Java exception Java Exception Interview Questions (2021 Latest edition) Juejin. Cn/post / 695644…
21 The Java virtual machine Java Virtual Machine Interview (2021 latest edition) Juejin. Cn/post / 695658…
22 Java collection Java Set Interview Questions (2021 Latest edition) Juejin. Cn/post / 695684…
23 Git Git Git Command (2021) Juejin. Cn/post / 695692…
24 Elasticsearch Elasticsearch (2021 Latest Edition) Juejin. Cn/post / 695840…
25 Dubbo Dubbo Interview Questions (2021 Latest edition) Juejin. Cn/post / 695842…

1. What is the use of multithreading?

1) Take advantage of multi-core CPU

With the progress of the industry, now notebook, desktop and even commercial application servers are at least dual-core, 4-core, 8-core and even 16-core are not uncommon. If it is a single-threaded program, then 50% of the dual-core CPU is wasted, and 75% of the 4-core CPU is wasted. The so-called “multithreading” on a single-core CPU is false multithreading. The processor only processes one piece of logic at a time, but the threads switch between them so fast that it looks like multiple threads are running “simultaneously”. Multi-threading on the multi-core CPU is the real multi-threading, it can make your multi-section of logic work at the same time, multi-threading, can really play the advantages of the multi-core CPU, to make full use of the PURPOSE of the CPU.

2) Prevent blocking

From the point of view of program efficiency, single-core CPU will not give full play to the advantages of multithreading, but will cause the thread context switch because of running multithreading on single-core CPU, and reduce the overall efficiency of the program. but

With a single-core CPU we still have to apply multithreading, just to prevent blocking. Imagine if a single-core CPU uses a single thread, and if that thread blocks, say, reading data remotely, and the peer doesn’t return and doesn’t set a timeout, your entire program will stop running before the data comes back. Multithreading prevents this problem. Multiple threads are running at the same time, and even if the code in one thread is blocked in reading data, it does not affect the execution of other tasks.

3) Easy to model

This is another advantage that is not so obvious. Let’s say you have A big task A, single-threaded programming, and it’s A lot to think about, and it’s A lot of trouble to model the entire program. However, if the big task A is broken down into several small tasks, task B, task C and task D, respectively build the program model, and run these tasks separately through multi-threading, it will be much simpler.

What is the difference between a thread and a process?

The main difference between processes and threads is that they are different ways of managing operating system resources. Processes have independent address Spaces, a crash of one process in protected mode does not affect other processes, and threads are just different execution paths within a process. Thread has its own stack and local variables, but there is no separate address space between threads, a thread dead is equal to the whole process dead, so multi-process procedures than multithreaded procedures robust, but in the process switch, the cost of resources is larger, the efficiency is poor. However, for concurrent operations that require simultaneous and variable sharing, only threads, not processes, can be used.

3. How can Java implement threads?

  • 1) Inherit Thread class to achieve multithreading
  • 2) Implementation of Runnable interface to achieve multithreading
  • Implement multithreading with returns using ExecutorService, Callable, and Future

4. What is the difference between start() and run() methods?

The multithreaded nature is only apparent when the start() method is called, and the code in the run() method is executed alternately in different threads. If only the run() method is called, the code is executed synchronously, and one thread must wait for all the code in its run() method to complete before another thread can execute its run() method.

5. How to terminate a thread? How do I gracefully terminate a thread?

Stop Stop is not recommended.

6. What are the states of a thread life cycle? How do they flow from one to the other?

NEW: Indicates that the thread has not been started yet.

RUNNABLE: indicates that the thread has triggered the start() call. The thread is officially started and in the running state.

BLOCKED: The thread is BLOCKED and waiting for the lock. For example, when the critical area is occupied by keywords such as synchronized and lock, the thread continues to run in RUNNABLE state once the lock is obtained.

WAITING: It indicates that a thread is in an unrestricted wait state, waiting for a special event to wake up. For example, a thread waiting through wait() waits for notify() or notifyAll(), and a thread waiting through Join () waits for the end of the target thread to wake up. Once a thread is woken up with an event, it enters the RUNNABLE state and continues running.

TIMED_WAITING: indicates that the thread has entered a time-limited wait, such as sleep(3000). After 3 seconds, the thread resumes RUNNABLE state and continues running.

TERMINATED: Indicates that the thread TERMINATED after execution is complete. Note that once a thread is started using the start method, it can never return to its original NEW state, nor can it return to the RUNNABLE state after it terminates

7. What is the difference between wait() and sleep() methods in threads?

Sleep and wait can both be used to give up the CPU for a certain amount of time. The difference is that if a thread holds the monitor for an object, sleep does not give up the monitor for that object, while wait does

8. What are the methods of multithreading synchronization?

Synchronized keyword, Lock Lock implementation, distributed Lock and so on.

9. What is a deadlock? How do I avoid deadlocks?

A deadlock is when two threads wait for each other to release an object lock.

10. How do multiple threads communicate with each other?

wait/notify

How does the thread get the result?

Implement Callable interface.

12, Violatile keyword function?

13. Create three threads T1, T2 and T3, how to ensure that they are executed in sequence?

Use join.

How to control only 3 threads running at the same time?

Use the Semaphore.

15. Why use thread pools?

We know that without a Thread pool, each Thread needs to create and run a new Thread(xxRunnable).start(). This is not a problem if there are fewer threads, but in real situations, multiple threads can be opened to maximize the efficiency of the system and programs. When the number of threads reaches a certain level, the CPU and memory resources of the system are exhausted, and frequent GC collections and pauses are also caused, because each creation and destruction of a thread consumes system resources, which is a significant performance bottleneck if threads are created for each task. Therefore, thread reuse in the thread pool greatly saves system resources, and it also destroys itself when the thread has no work to do for a period of time, rather than remaining in memory.

Common thread pools and how they work.

What is the difference between the submit() and execute() methods for starting a thread in a thread pool?

What is the difference between CyclicBarrier and CountDownLatch?

Two similar looking classes, both under java.util.concurrent, can be used to indicate that code is running at a point. The difference is that:

1. Once a CyclicBarrier thread reaches a certain point, the thread stops running and does not restart until all threads have reached this point. CountDownLatch is not. After a thread runs to a certain point, it just gives a value of -1, and the thread continues to run 1

2.CyclicBarrier can only evoke one task, CountDownLatch can evoke multiple tasks

3.CyclicBarrier can be reused, but CountDownLatch cannot be reused. If the CountDownLatch is 0, the CountDownLatch is no longer available

What is a live lock, hunger, no lock, deadlock?

20. What are atomicity, visibility and order?

21. What is a daemon thread? What’s the use?

What is a daemon thread? The corresponding daemon thread is the user thread. The daemon thread is the daemon user thread. When the user thread is finished, the daemon thread will follow. The daemon thread must be accompanied by the user thread. If there is only one daemon thread in an application and no user thread, the daemon thread will exit naturally.

22. What happens when an exception occurs while a thread is running?

The thread will stop execution if the exception is not caught. Thread. UncaughtExceptionHandler is used for uncaught exception handling Thread sudden interruption of an embedded interface. When an uncaught exception will be built into a Thread interrupts when the JVM will use Thread. GetUncaughtExceptionHandler () to query the Thread UncaughtExceptionHandler and as a Thread and exceptions The arguments are passed to the uncaughtException() method of the handler for processing.

What is the use of thread yield()?

The Yield method suspends the currently executing thread object to allow other threads of the same priority to execute. It is a static method and only guarantees that the current thread will give up CPU usage, but does not guarantee that other threads will be able to use CPU usage. A thread that performs yield() may be executed immediately after entering the pause state.

24. What is a reentrant lock?

The so-called re-entrant lock refers to the unit of thread. When one thread acquires the object lock, the thread can acquire the lock on the object again, while other threads cannot.

25. What is the use of Synchronized?

Lock class, lock method, lock code block

26. What does the Fork/Join framework do?

Large tasks are automatically divided into small tasks, executed concurrently, and the results of small tasks are merged.

27. What exceptions can be caused by too many threads?

Too many lines can cause stack overflows and can also cause heap exceptions

Talk about thread-safe and unsafe collections.

The most commonly used set of Maps in Java is the HashMap, which is thread-unsafe. Look at the following two scenarios:

1, when using local variables in a method, local variables belong to the current thread level variables, other threads can not access, so there is no thread safety problem. 1

2. When used with singleton member variables? In this case, multiple threads are accessing the same HashMap, and operating on the same HashMap is a thread-safe problem.

29. What is CAS algorithm? What are the applications in multithreading.

How do I check if a thread has a lock?

Java. Lang. Thread# holdsLock method

Jdk troubleshooting multithreading problems with what command?

jstack

32. What should be paid attention to in thread synchronization?

1. Minimize the scope of synchronization to increase system throughput.

2. Distributed synchronization lock is meaningless. Use distributed lock.

3, to prevent deadlocks, pay attention to the lock sequence.

What are the prerequisites for thread wait()?

To be used in synchronous blocks.

34. What should be noted about the use of Fork/Join framework?

If the task disassembly is very deep, the number of threads in the system accumulates, leading to a serious decline in system performance. If the function call stack is very deep, it will cause stack memory overflow;

How do threads pass data to each other?

What are some ways to ensure visibility?

Synchronized and viotatile

37, Say a few commonly used Lock interface implementation Lock.

Already, the ReadWriteLock

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

The purpose of ThreadLocal is to provide local variables within a thread that operate for the lifetime of the thread, reducing the complexity of passing some common variables between functions or components within the same thread. It is used to solve database connection, Session management, etc.

39. What is ReadWriteLock for?

ReadWriteLock is a read/write lock interface. ReentrantReadWriteLock is a concrete implementation of the ReadWriteLock interface. It enables read and write separation. Read and write, write and read, and write and write are mutually exclusive, improving read and write performance.

40. What is FutureTask?

FutureTask represents an asynchronous operation task. FutureTask can pass in a 1-body implementation class of Callable, which can wait for the result of the asynchronous operation task, determine whether the task has been completed, cancel the task and other operations.

How do I wake up a blocked thread?

42. How can immutable objects help multithreading?

43. What does multithreaded context switching mean?

44. What thread scheduling algorithm is used in Java?

What does thread.sleep (0) do?

46, What is the Java memory model? Which areas are shared by threads and which are not?

What is the optimistic lock and pessimistic lock?

[root@hashtable] [root@hashtable]

Which is better, synchronous method or synchronous block?

What is a spin lock?

Spin locks are implemented by having the current thread execute continuously in the loop body, and then enter the critical section when the loop condition is changed by other threads.

51, Which is better, Runnable or Thread?

Java does not support multiple inheritance of classes, but allows you to implement multiple interfaces. So if you want to inherit from other classes, Runnable is better in order to reduce coupling between classes.

52, What is the difference between notify and notifyAll in Java?

Notify () doesn’t wake up a specific thread, so it’s only useful if one thread is waiting.

NotifyAll (), on the other hand, awakens all threads and allows them to compete for locks, ensuring that at least one thread can continue running.

53, Why are wait/notify/notifyAll methods not included in thread?

54. Why are wait and notify called in synchronous blocks?

55. Why should you check the wait condition in a loop?

What is the difference between a heap and a stack in Java?

57. How do you get a thread stack in Java?

How to create a thread-safe singleton pattern?

59. What are blocking methods?

A blocking method means that the program waits for the method to complete and does nothing else. The ServerSocket Accept () method waits for the client to connect. Blocking here means that the result of the call is returned before the current

The thread is suspended and will not return until the result is obtained. In addition, there are asynchronous and non-blocking methods that return before the task is complete.

What happens when the thread pool queue is full when a task is submitted?

When the number of threads is smaller than maximumPoolSize, a new thread is created to process it, and when the number of threads is greater than or equal to maximumPoolSize, a rejection policy is executed.