[Series] preparing for spring recruit the most complete concurrent programming interview Zhenti resolution, teach you how to beating and hanging interviewer

1, the three elements of concurrent programming?

1, atomicity

Atomicity refers to one or more operations, or all other operations are not performed, and during the execution of
For interrupting, or to all without execution.

2, visibility

It refers to the visibility of the plurality of threads operating a shared variable, in which a thread to modify variables, other
Threads can see the results of changes immediately.

3, orderliness

Ordering, i.e., program execution sequence performed in the order code. 

2, way to achieve visibility of what?

synchronized or Lock: to ensure that only one thread at the same time acquire the lock code execution, before the release of the latest value of the lock flushed to main memory, to achieve visibility. 

3, multi-threaded value?

1, play the advantages of multi-core CPU 

Multi-threaded, can really play the advantages of multi-core CPU to achieve the purpose of full use of CPU, multi-threaded approach to the completion of several things simultaneously without interfering with each other. 

2, to prevent clogging

From a procedural point of view of operating efficiency, single-core CPU will not only play the advantages of multi-threaded, multi-threaded run because it will lead to thread context switches, and reduce the overall efficiency of the program on a single core CPU. But we still have to single-core CPU multi-threaded applications, it is to prevent clogging. Just think, if it is before the single-core CPU using a single thread, so as long as this thread is blocked, say a data remotely read it, the peer has not yet been returned and no set time-out, then your entire program in return data back stopped working. Multithreading can prevent this problem, a number of threads to run simultaneously, even if a code execution thread to read data blocked, it will not affect the execution of other tasks. 

3, to facilitate the modeling 

This is another advantage of the not so obvious. Suppose you have a large task A, single-threaded programming, then you must consider a lot, build the entire program model is too much trouble. But if this great task A broken down into several small tasks, task B, task C, task D, were established program model and run these tasks through multi-threading, respectively, then a lot simpler.

4. What are the ways to create a thread? 

1, inheritance Thread class to create a thread class
2, create threads through the Runnable interface class
3, create a thread through Callable and Future
4, created by a thread pool

5, three ways to create a contrast thread? 

1, using achieve Runnable, Callable way to create multi-threaded interface.

Advantages are: 

Thread class implements Runnable interface or just Callable interface, you can also inherit from other classes. In this way, multiple threads may share the same target object, is the same for a plurality of threads to deal with a case where the same resources, which can be separated to form a clear model of the CPU, code and data, to better reflect the object-oriented thinking. 
Disadvantages are:

Programming is slightly more complicated, if you want to access the current thread, you must use Thread.currentThread () method. 

2, use the Thread class inheritance to create multi-threaded 

Advantages are: 
Write simple, if you need access to the current thread, you do not need to use Thread.currentThread () method, the direct use this to get the current thread. 
Disadvantages are:

Thread class Thread class has been inherited, so can not inherit other parent. 

3 difference, Runnable and Callable of

1, Callable predetermined (override) is a method call (), Runnable predetermined (override) method is run ().
2, the task can be performed Callable return value, and the task is not Runnable return value.
3, Call method may throw an exception, run method can not.
4, can get a running task Callable Future object representing the result of the asynchronous computation. It provides a method of checking computation is complete, to wait for the completion of calculation, and calculation of the search result. By Future object can understand the implementation of the mandate, to cancel the execution of the task, but also get the results. 

6, state of the thread flow diagram

Life cycle and five basic state of the thread:

![img_2.png][img_2.png]复制代码

7, Java thread has the fifth basic state

1, the new state (New) : After the object created when a thread that enters the new status, such as: Thread t
= new MyThread();
2, ready state (Runnable) : When the start () method calls the thread object (t.start ();), thread
That is, into a ready state. Thread in the ready state, is illustrative of this thread we are ready, at any time
Waiting for the CPU scheduled for execution, not to say that the implementation of the t.start () This thread will be executed immediately;
3, running state (Running) : When the CPU thread scheduling is started in a ready state, then thread
He was able to really perform, that is, into the operational state. NOTE: The state is ready to enter into the unique operating conditions
Mouth, that is to say, in order to enter the running thread execution state, first of all must be in a state of readiness;
4, blocking state (Blocked) : running the thread for some reason, temporarily give up CPU
The right to use, stop execution, this time into the block until it enters the ready state, then a chance
CPU time is called to enter into the operation.
Depending on the reason for blocking generated, blocked state can be divided into three types:
1, waiting for blocking: a thread of execution running state wait () method, so that the thread enters the wait state obstruction;
2, synchronous blocking: get synchronized thread synchronization lock failure (because the lock was occupied by other threads),
It will enter synchronous blocking state;
3, blocking other: sleep by the calling thread () or join () or issue an I / O request, the thread will enter
To blocking state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing
When completed, the thread into the ready state again.
5, the death state (Dead) : thread execution is over or due to abnormal exit the run () method, the thread end
Life cycle

8. What is the thread pool? What are the different ways to create? 

Advance the thread pool is to create several threads, if there is need to deal with the task, the thread pool thread will handle the task, after processing threads and will not be destroyed, but waiting for the next task. Because creating and destroying threads are consuming system resources, so when you want to frequent creating and destroying threads can consider using the thread pool to improve system performance. java java.util.concurrent.Executor provides an implementation of the interface used to create a thread pool.

9 the four thread pool is created:

1, newCachedThreadPool create a thread pool cacheable
2, newFixedThreadPool create a fixed-size thread pool, you can control the maximum number of concurrent threads.
3, newScheduledThreadPool create a fixed-size thread pool to support regular and periodic task execution.
4, newSingleThreadExecutor create a single-threaded thread pool, use it only to perform the task only worker threads.

10, the thread pool advantage?

1, reuse existing threads, reducing the overhead of object creation destroyed.
2, can effectively control the maximum number of concurrent threads, improve utilization of system resources, while avoiding excessive competition for resources, to avoid clogging.
3, there is provided a timing executed to perform regular, single-threaded, concurrent control. 

11, commonly used utility classes concurrent What?

1、CountDownLatch
2、CyclicBarrier
3、Semaphore
4、Exchanger 

12, the difference CyclicBarrier and CountDownLatch 

1, CountDownLatch simply means that a thread to wait until another thread is waiting for his execution were completed and calls countDown () method to be notified when the current thread can continue execution.
2, cyclicBarrier all threads waits until all threads are ready to enter the await () method after all threads started!
3, CountDownLatch counter can only be used once. The counter can be used CyclicBarrier reset () method to reset. So CyclicBarrier can handle more complex business scenarios, such as if calculation error occurs, you can reset the counter, and let the threads are executed once again.
4, CyclicBarrier also provides other useful methods, such as getNumberWaiting ways to get the number of threads CyclicBarrier blocked. isBroken method is used to know whether the blocked thread is interrupted. Returns true if interrupted, otherwise false. 

13, the role of synchronized?

In Java, synchronized keyword is used to control the thread synchronization, that is, in a multithreaded environment, the control code segments are not synchronized simultaneous execution of multiple threads.
synchronized either added to the piece of code may be added to the method.

14, the role of the volatile keyword

For visibility, Java provides the volatile keyword to ensure visibility.
When a shared variable is declared volatile, it will ensure that the modified values ​​will be updated immediately to the main memory, when there are other threads need to read, it will read the new value to memory.
From a practical point of view, an important role is volatile and CAS combined to ensure the atomicity, details can be found under the category java.util.concurrent.atomic package, such AtomicInteger. 

15. What is CAS

CAS is an abbreviation compare and swap, that is what we call comparative exchange.
cas is a lock-based operation, and is optimistic locking. In java lock into optimistic and pessimistic locking. Pessimistic lock is locked resource, such as after a thread releases the lock before obtaining the lock, the next thread can access. The optimistic locking taking a broad approach to processing resources by not locking in some way, such as to obtain the data by adding to the record version, a more pessimistic locking performance has greatly improved.
CAS operation includes three operands - a memory location (V), is expected to original value (A) and the new value (B). If the value of the memory address and the value of A which is the same, then the values ​​will be updated to the memory inside B. CAS is to get the data through an infinite loop, Ruoguo cycle in the first round, a thread gets inside the address value is modified b-threaded, then a thread needs to spin cycle to the next possible opportunity to perform. Most java.util.concurrent.atomic package under the category is implemented operating with a CAS (AtomicInteger, AtomicBoolean, AtomicLong). 

16, CAS issues

1, CAS ABA likely to cause problems

A thread a numerical value into a b, and then they changed it to a, CAS considered at this time has not changed, in fact, has changed too, and the solution to this problem you can use the version number to identify each operation plus a version 1 . In java5 it has been provided AtomicStampedReference to solve the problem.

2, can not guarantee atomicity code block

CAS atomicity operation mechanism to ensure knowledge of a variable, but can not guarantee the atomicity of the entire code block.
Such as the need to ensure that three variables common to update atomicity, you have to use a synchronized.

3, CAS cause an increase in CPU utilization

He said before the CAS process there is a cycle of judgment, if the thread has not acquired status, cpu resources will always be occupied.

17. What is the Future? 

In concurrent programming, we often use non-blocking model, to achieve the three previous multi-threaded, whether inherited or implement thread class runnable interfaces, they can not guarantee the implementation of previous results obtained. By implementing Callback interface and can be received by the multi-threaded execution result Future.

Future represents the result may not have a complete asynchronous tasks for this result can be added Callback in order to make the appropriate action after the task execution success or failure. 

18. What is the AQS

AQS AbustactQueuedSynchronizer is short, it is a Java-based tools to improve the level synchronization, the synchronization state represented by a variable of type int, and provides a series of CAS operations to manage the synchronized state. 
AQS is used to build a frame lock and a synchronizer, using AQS can be constructed simply and efficiently a large number of widely synchronizer, such as we mentioned ReentrantLock, Semaphore, such as other ReentrantReadWriteLock, SynchronousQueue, FutureTask like are It is based on the AQS. 

19, AQS supports two synchronization methods:

1, Exclusive formula
2, shared
Such user-friendly implement different types of synchronization component of ReentrantLock as exclusive, shared, such as Semaphore, CountDownLatch, such as modular ReentrantReadWriteLock. In short, AQS provides underlying support for the use, how to assemble achieve, users can play for free.

20, what is ReadWriteLock

First clear look at, not to say ReentrantLock bad, just ReentrantLock sometimes have limitations. If you use ReentrantLock, may itself be in order to prevent the thread A write data, data inconsistencies thread B in the read data caused, but this way, if the thread C in reading data, the thread D also read data, the read data will not change the data, it is not necessary lock, but still locked up, reducing the performance of the program. Because of this, before the birth of the read-write lock ReadWriteLock. ReadWriteLock interfaces is a read-write lock, is a specific implementation ReentrantReadWriteLock with ReadWriteLock interface, realizes the separation of read and write, a read lock is shared, exclusive write lock is not mutually exclusive write and read, read and write, will mutually exclusive between the write and read, write, and write, read and write performance improves.

21, what is FutureTask

This fact has mentioned earlier, FutureTask indicates that the task of an asynchronous operation. FutureTask which can pass a Callable implementation class may be made to wait for access to the results of the task asynchronous operations, has been completed is determined whether to cancel the operation tasks. Of course, since FutureTask also Runnable interface implementation class, so FutureTask also can be placed in the thread pool.

The difference between 22, synchronized and the ReentrantLock

It is synchronized and if, else, for, while the same keyword, ReentrantLock is class, which is the essential difference between the two. Since ReentrantLock is a class, then it provides more flexibility than the synchronized characteristics can be inherited, there are ways you can, you can have a variety of class variables, scalability synchronized ReentrantLock than reflected in the points:
  1. ReentrantLock can be set to acquire the lock wait time, thus avoiding deadlock
  2. ReentrantLock can obtain information on the various locks
  3. ReentrantLock flexibility to achieve multi-channel notification
In addition, both the lock mechanism is actually not the same. ReentrantLock low-level calls that park Unsafe methods of locking, synchronized operation should be the subject header mark word, which I can not determine. 

23. What is the optimistic and pessimistic locking

1, optimistic lock: As its name suggests, for thread safety issues between concurrent operations generated optimistic state, optimistic locking that competition does not always happen, so it does not need to hold the lock, the comparison - the replacement of these two It operates as an atomic operation attempts to modify variables in memory, if said conflict fails, then there should be a corresponding retry logic.
2, pessimistic locking: or, as its name suggests, for thread safety issues between concurrent operations generated a pessimistic state, pessimistic locking that competition will always happen, so every time a resource operation, will hold an exclusive lock, like synchronized, willy-nilly, operating directly on the lock on the resource. 

24, thread A thread B know how to modify the variables

  1. volatile modifying variables
  2. synchronized modification method modify variables
  3. wait/notify
  4. while polling 

25, synchronized, volatile, CAS compare

  1. synchronized pessimistic locks, are preemptive, other threads will cause clogging.
  2. volatile multi-threaded shared variables provide visibility and prohibit instruction reordering optimization.
  3. CAS is based on optimistic locking conflict detection (non-blocking) 

26, what is the difference between sleep and wait method method? 

This question is often asked, sleep and wait method method can be used to give up some CPU time, except that if the thread holding an object monitor, sleep method does not give up this object's monitor, wait method will give up this object monitor

27. What ThreadLocal that? What is the use?

ThreadLocal thread is a local copy of the variable tools. Mainly for the private copy of the object stored in the thread and the thread to do a mapping, variable between individual threads without disturbing each other, in a highly concurrent scenarios can be achieved without state calls, especially for dependent variable values ​​each thread does not make sense complete scenes operations. Simply put ThreadLocal is a kind of space for time approach, in which each Thread to maintain an open address method to achieve ThreadLocal.ThreadLocalMap, data isolation, data is not shared, naturally, there is no question of the security thread.

28, why the wait () method, and notify () / notifyAll () method to be invoked in the sync blocks

This JDK is mandatory, wait () method, and notify () / notifyAll () method must first obtain the object before calling lock 

29, which has several multi-thread synchronization method? 

Synchronized keyword, Lock locks for distributed lock. 

30, thread scheduling policy

Thread scheduler selects the highest priority thread to run, however, if the following occurs, it will terminate the thread running:
  1. Thread body called yield ways to get out of the right to occupy the cpu
  2. Thread body called sleep method enables the thread to sleep
  3. IO operation is blocked because the thread
  4. In addition a higher priority thread appears
  5. In the system supports time slice, the thread's time slice runs out 

31, what is the degree of concurrency ConcurrentHashMap

ConcurrentHashMap concurrency is the size of the segment, the default is 16, which means that there can be up to 16 threads simultaneously operating ConcurrentHashMap, which is the biggest advantage of the Hashtable ConcurrentHashMap, in any case, there are two threads simultaneously Hashtable can get the Hashtable data?

32, how to find out which Linux environment using CPU longest thread

  1. pid acquisition projects, jps or ps -ef | grep java, have talked about this in front
  2. top -H -p pid, the order can not be changed

33, Java and how to avoid deadlock?

Java is a programming in a deadlock situation in which two or more threads are permanently blocked, Java deadlock situation at least two threads and two or more resources.
Java root cause of deadlock are: Cross occurred when applying for a closed-loop application lock. 

34, the cause of a deadlock

1, a plurality of threads related to a plurality of locks, these locks exist crossing, it may cause a lock-dependent closed-loop. 

For example: in the case of threads get locked down A and did not release the application lock B, then, it has gained another thread lock B, and B before releasing the lock must first obtain a lock A, and therefore closed loop occurs, the deadlock cycle .

2, the default lock application operation is blocked.

So to avoid deadlock, it is necessary in the case of a face lock multiple objects intersect, we must carefully examine all the methods in the class of these objects, whether there is a possibility lead to dependence lock loop. All in all, try to avoid other objects and methods delay synchronization method calls in a synchronous approach. 

35, how to awaken a blocked thread

If the thread is blocked because the call wait (), sleep () or join () method caused, can interrupt threads, and to wake it up by throwing InterruptedException; if the IO thread encounters a blockage, do nothing, because the operating system IO implementation, Java code and no way to directly access to the operating system. 

36, immutable objects was going to help multithreading

There is a problem mentioned in the foregoing, the immutable object to ensure visibility of memory objects, to read immutable object does not require additional synchronization means to enhance the efficiency of code execution.

37, what is the multithreaded context switching

Multi-thread context switch refers to the control of the CPU switch from an already running thread to another place and wait for the process of obtaining execution of the CPU threads. 

38, if you submit the task, the thread pool queue is full, then what will happen

Here we distinguish between: 
1. If you are using LinkedBlockingQueue unbounded queue, the queue is unbounded, then it does not matter, continue to add tasks to the blocking queue waiting to be executed, because LinkedBlockingQueue can be considered almost an infinite queue, you can store unlimited tasks
2, if it is bounded queue used such ArrayBlockingQueue, the first task will be added to ArrayBlockingQueue in, ArrayBlockingQueue full, based on the number of value added threads maximumPoolSize, if increasing the number of threads or handle, however, ArrayBlockingQueue continue full, then the RejectedExecutionHandler treatment strategies will be used to refuse full task, the default is AbortPolicy

39 What Java thread scheduling algorithm is used

Preemptive. After a thread run out of CPU, operating system will be calculated based on a total priority thread priority, thread starvation situation and other data and assign the next time slice to execute a thread. 

40, what is the thread scheduler (Thread Scheduler) and time slicing (TimeSlicing)?

Thread scheduler is an operating system service, which is responsible for the state of Runnable thread allocation of CPU time. Once we create a thread and start it, it will depend on the implementation of the implementation of the thread scheduler. Refers to the process time slice is the available CPU time assigned to an available thread Runnable. Allocates CPU time can thread priority or thread wait on. Thread scheduling is not controlled by the Java virtual machine, so the application to control it is a better choice (that is to say do not let your application depends on the priority of the thread). 

41, what is a spin 

Many synchronized code inside just some very simple code, very fast execution time, then wait for the thread lock might be a less worthy of operation, because the thread blocking issues related to the user mode and kernel mode switching. Since the code execution inside the synchronized very fast, let's wait for the lock thread is not blocked, but do busy circulating in the border synchronized, this is spin. If you do not find that many times get busy cycle lock, and then blocked, this may be a better strategy.

42, what is Java Concurrency API interfaces in Lock (Lock interface) that? Contrast synchronization is there any advantage? 

Lock Interface sync blocks than the synchronization method and provide lock operation more scalable. They allow a more flexible structure, may have completely different properties, and may support a plurality of conditions related to the object classes. Its advantages are:
  1. You can lock fairer
  2. The thread can interrupt response time of waiting for the lock
  3. It allows thread tries to acquire the lock and returns immediately when unable to obtain the lock or wait for some time
  4. Can, acquiring and releasing locks in a different order in a different range

Security thread 43, the singleton

Commonplace problem, the first thing to say is thread-safe means Singleton pattern: an instance of a class will only be created once out in a multithreaded environment. There are many cases of single mode of writing, I summarize:
  1. Writing hungry man single-mode example: Thread safety
  2. Lazy writing style Singleton pattern: non-thread-safe
  3. Double lock detection wording singletons: Security Thread

44, Semaphore what role

Semaphore is a semaphore, its role is to limit the number of concurrent certain code block. Semaphore has a constructor, you may pass an int type integer n, represents a piece of code at most n threads can access, if exceeded n, then please wait until a thread completes this code block, the next thread re-entry. It can be seen that if the incoming Semaphore constructor type integer int n = 1, the equivalent into a synchronized.

45, what Executors class is?

Executors provides tools method Executor, ExecutorService, ScheduledExecutorService, ThreadFactory and Callable classes. Executors can be used to easily create a thread pool

46, the constructor of the Thread class, is called a static block which thread

This is a very tricky and tricky questions. Remember: Thread class constructor, static block is where the new thread is the thread class called, and run the code inside the method is being called by the thread itself. 
If the above statement makes you feel confused, then I, for example, assume that the new Thread2 the Thread1, main function in the new Thread2, then:
1, Thread2 constructor, static blocks are called the main thread, Thread2 the run () method is
Thread2 own call
2, Thread1 constructor, static blocks are called Thread2, Thread1 the run () method is
Thread1 own call

47, synchronization method and synchronized block, which is the better choice? 

Sync blocks, which means that code outside the sync block is asynchronous, which further enhance the efficiency of the overall process than synchronous code. Please know that a principle: when synchronization as possible. 

48, Java threads will cause too much anything unusual?

1, life cycle cost is very high thread

2, excessive consumption of CPU resources

If the number of threads that can run more than the number of available processors, then there will be idle threads. A large number of empty
Idle thread will occupy a lot of memory, to bring pressure on the garbage collector, and a large number of threads competing for CPU
It will also have a performance overhead when other resources.

3, reducing the stability of

JVM there is a limit on the number of threads can be created, this limit will vary from platform to platform,
And receiving a plurality of factors, including the JVM startup parameters, requests the Thread stack constructor
Sizes, and restrictions on the underlying operating system thread and so on. If the destruction of these restrictions, it may throw
OutOfMemoryError exception.

to sum up:

[Series] preparing for spring strokes on kafka, BAT manufacturers like how to ask?

[Series] preparing for spring strokes soul 28 ZooKeeper ask, teach you how to get the interviewer!

[Series] preparing for spring strokes interview Zhenti latest Linux 45

[Series] over the years preparing for spring recruit high-frequency comb on MySQL interview Zhenti

[Series] springBoot preparing for spring strokes soul 22 ask!

[Preparing for the spring series of strokes] 50 micro-service interview Zhenti Detailed

[Preparing for the spring series of strokes] 27 MyBatis interview Zhenti Detailed

Resdis 40 manufacturers asked the soul, teach you how to get the interviewer

Spring is about to move to, and compiled some classic face questions manufacturers often test, and there is a need friends can micro-channel public number: Java programmers to gather.



Guess you like

Origin juejin.im/post/5e143e97e51d45414e6ab100