Multithreading interview questions (with answers)

1, the three elements of concurrent programming?

1) atomicity

  • Atomicity refers to one or more operations, and performing either all other operations will not be interrupted during execution, or to all without execution.

2) visibility

  • Refers to the visibility of the plurality of threads operating a shared variable, wherein the variable modify a thread, other threads can immediately see the results of changes.

3) ordering

  • 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) take advantage 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) prevent obstruction

  • 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, 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) 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. Comparison of three ways to create a thread?

1) to 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) create multiple threads using the Thread class inheritance way

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) the difference of Runnable and Callable

  • Callable predetermined (override) is a method call (), Runnable predetermined (override) method is run ().
  • Callable tasks can be executed after the return value, and Runnable task is not the return value.
  • Call method may throw an exception, run method can not.
  • Run Callable task can get a Future object that represents the result of an 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.

Life cycle and five basic state of the thread:

 

 

6.Java thread has the fifth basic state

  • 1) a new state (New): After the object created when a thread that enters the new status, such as: Thread t = new MyThread ();
  • 2) the ready state (Runnable): When the start () method (t.start (the calling thread object);), the thread that is ready state. Thread in the ready state, is illustrative of this thread is ready, waiting for the CPU scheduled for execution at any time, not to say that the implementation of the t.start () This thread will be executed immediately;
  • 3) run state (Running): When the CPU thread scheduling is started in a ready state, and this time was able to really execute threads that go into run mode. Note: ready state is the only means of access to the operating state, that is, the thread execution in order to enter the running state, first of all must be in a state of readiness;
  • 4) blocking state (Blocked): running the thread for some reason, temporarily give up the right to use the CPU, stop the execution, this time into the block until it enters the ready state, have a chance to be called again CPU to go into run mode.
  • Depending on the reason for blocking generated, blocked state can be divided into three types:
  • 1. Wait for blocking: a thread of execution wait state operation () method, so that the thread enters the wait state obstruction;
  • 2. synchronous blocking - thread synchronization lock failure in obtaining synchronized (because the lock was occupied by another thread), it will enter synchronous blocking state;
  • 3. Other blocked - by sleep () or join the calling thread () or issued I / O request, the thread into the blocked state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.
  • 5) death state (Dead): thread execution is over or due to abnormal exit the run () method, the thread end of the life cycle.

 

7. 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.

 

8. four kinds of 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.

 

9. The advantage of a thread pool?

  • 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) provides timing executed to perform regular, single-threaded, concurrent control.

 

10. Common concurrency tools What?

  • CountDownLatch
  • CyclicBa
  • rrier
  • Semaphore
  • Exchanger

 

The difference 11.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.

 

The role of 12.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.

 

The role of 13.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.

 

14. 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).

 

15. 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) does not guarantee the atomicity of code blocks

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.

 

16. 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.

 

17. 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.

 

18. 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.

 

What is 19.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.

 

What is 20.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 21.synchronized and 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 set the waiting time to acquire the lock, thus avoiding the deadlock
  • (2) ReentrantLock may acquire various information lock
  • (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.

 

22. 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 will compare - to replace two actions as one atomic operation attempts to modify variables in memory, if said conflict fails, then there should be a corresponding retry logic.
  • (2) pessimistic lock: 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.

 

23. A thread B thread know how to modify the variables

  • volatile modifying variables
  • synchronized modification method modify variables
  • wait/notify
  • while polling

 

24.synchronized, volatile, CAS compare

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

 

25.sleep method and wait method What is the difference?

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

 

What 26.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 maintains ThreadLocal.ThreadLocalMap a law to address open implementation, data isolation, data is not shared, naturally, there is no question of the security thread.

 

27. Why 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

 

28. What are the multi-thread synchronization method?

Synchronized keyword, Lock locks for distributed lock.

 

29. The 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) Since the IO operation thread is blocked
  • (4) In addition a higher priority thread appears
  • (5) in a system supporting time slice, the time slice expires thread

 

What is the degree of concurrency 30.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?

 

Under 31.Linux environment How to find which thread uses the CPU longest

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

 

32.Java deadlock and how to avoid?

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.

 

33. 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.

 

34. how 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.

 

35. 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.

 

36. What is the context of multi-threaded switch

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.

 

37. If you submit the task, the thread pool queue is full, then what happens

Here we distinguish between:

  • 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
  • If it is bounded queue used such ArrayBlockingQueue, the first task will be added to the ArrayBlockingQueue, ArrayBlockingQueue full, will increase the number of threads maximumPoolSize value, if increasing the number of threads or handle, however, continue ArrayBlockingQueue full, it will be used RejectedExecutionHandler processing tasks rejection policy is full, the default is AbortPolicy

 

What thread scheduling algorithm is used in 38.Java

Preemptive: After a thread runs CPU, operating system will calculate the next general priorities and allocate a time slice to execute a thread based on the thread priority, thread hunger and other data.

 

39. What is the thread scheduler (Thread Scheduler) and time slicing (Time Slicing)?

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).

 

 

40. 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.

 

What 41.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:

  • You can lock fairer
  • The thread can interrupt response time of waiting for the lock
  • Allows thread tries to acquire the lock and returns immediately when unable to obtain the lock or wait for some time
  • Can, acquiring and releasing locks in a different order in a different range

 

42. The security thread Singleton pattern

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:

  • Writing (1) starving single mode embodiment: Security Thread
  • Writing (2) single idler embodiment mode: non thread-safe
  • Writing (3) Double-checked locking singletons: Security Thread

 

What is the role 43.Semaphore

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.

 

What 44.Executors class is?

Executors provides tools method Executor, ExecutorService, ScheduledExecutorService, ThreadFactory and Callable classes.

Executors can be used to easily create a thread pool

 

45. Thread class constructor, 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:

  • Constructor (1) Thread2 static block is the main thread calls, Thread2 the run () method is invoked own Thread2
  • The method of construction (2) Thread1 static blocks are called Thread2, Thread1 the run () method is invoked their Thread1

 

46. ​​The 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.

 

47.Java number of threads will cause too much anything unusual?

  • Life-cycle cost 1) very high thread
  • 2) consume excessive 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 idle threads will take up a lot of memory, to bring pressure on the garbage collector, and a large number of threads will incur the overhead of other performance when competing for CPU resources.

  • 3) reduce the stability of

There is a limit on the JVM creates the number of threads, this limit will vary from platform to platform, and subjected to a plurality of factors, including the JVM startup parameters, the Thread constructor stack size of the request, and the underlying operating restrictions on the system thread and so on. If the destruction of these restrictions, you may throw an OutOfMemoryError.

 

38. What are the ways to create a thread?

  • 1) Create a thread class inheritance Thread class
  • 2) create threads through the Runnable interface class
  • 3) Create a thread through Callable and Future
  • 4) Create a thread pool by

 

Guess you like

Origin www.cnblogs.com/cainiao-chuanqi/p/11285751.html