In 2020 the most comprehensive multi-threaded face questions summary to help you "gold and three silver four" over five Killing Six!

In 2020 the most comprehensive multi-threaded face questions summary to help you "gold and three silver four" over five Killing Six!

1, multi-thread what's the use?

  • 1) play the advantages of multi-core CPU
    with the progress of industry, and now laptops, desktops and even commercial application servers are also at least a dual-core, 4-core, 8-core or 16-core is also not uncommon, if it is single-threaded program, then on a dual-core CPU is wasted by 50% on a 4-core CPU is wasted by 75%. On a single core CPU so-called "multi-threaded" That is false multithreaded, processor will only deal with the same time period of logic, but faster than switching between threads, looked like multiple threads "simultaneously" run Bale. Multi-threading on multi-core CPU is a true multi-threaded, it allows you to work at the same logic multi-segment, multi-threaded, can really play the advantages of multi-core CPU to achieve the purpose of full use of the CPU.

  • 2) prevent obstruction
    from a procedural point of view of operating efficiency, single-core CPU multithreading not only will not play advantage, because it will lead to running multi-threaded thread context switching in a single-core CPU, while reducing the overall efficiency of the procedure. 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) 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.

2. What is the difference between threads and processes?

  • The main difference between processes and threads is that they are different operating system resource management.
  • Processes have separate address space, after a process crashes, will not have an impact on other processes in protected mode, and the thread is just a process of different execution paths.
  • Thread has its own stack and local variables, but there is no separate address spaces between the threads, a thread to die is tantamount to the whole process dies, so the program than multi-process multi-threaded programs robust, but in the process of switching, consuming greater resource efficiency to be worse.
  • But for some of the requirements at the same time and have to share the concurrent operation of certain variables, only with thread, the process can not be used.

3, Java thread, which has several ways to achieve?

  • 1, inheritance Thread class implements multithreading
  • 2, to achieve Runnable interface to achieve multi-threaded mode
  • 3, using ExecutorService, Callable, Future returns the results achieved have multithreading

4, start a thread method start () and run () What is the difference?

  • Only call the start () method, will exhibit characteristics of a multi-threaded, different threads run () method code inside alternately executed. If you just call the run () method, the code is executed synchronously, must wait for a thread's run () method after the code inside all is finished, another thread can execute its run () method code inside.

5, how to terminate a thread? How to gracefully terminate the thread?

  • stop termination is not recommended.

6, the life cycle of a thread, which has several state? How to transfer between them?

  • NEW: There is no doubt represents the thread you just created, has not yet started.
  • RUNNABLE: indicates that the thread has been triggered start () invoke, officially launched thread, the thread is running in the state.
  • BLOCKED: represents the thread to block waiting to acquire a lock, such as encounter synchronized, lock and other keywords such as the occupancy of the critical region, once the lock is to be acquired RUNNABLE state continues to run.
  • WAITING: indicates that the thread is not restricted waiting, waiting for a special event to re-awaken, such as waiting for a notify () or notifyAll () method wait () method waiting threads, a thread waits by the join () method waits the end goal thread runs wake, wake up the thread once through the relevant events, the thread into the RUNNABLE state continues to run.
  • TIMED_WAITING: indicates that the thread has entered a time of waiting, such as sleep (3000), re-thread RUNNABLE state continues to run after waiting for 3 seconds.
  • TERMINATED: After represents a thread of execution is completed, the termination status. It should be noted that the state can no longer return to RUNNABLE start after start method can no longer return to the initial state NEW, thread by thread to terminate once

7. What is the difference in the thread wait () and sleep () 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

8, which has several multi-thread synchronization method?

  • Synchronized keyword, Lock locks for distributed lock.

9. What is a deadlock? How to avoid deadlocks?

  • Deadlock is waiting for the other two threads each lock release objects.

10, how to communicate between multiple threads?

  • wait/notify

11, how to get the thread returns the result?

  • Implement Callable interface.

12, the role of violatile keywords?

  • A very important issue is that each study, multi-threaded applications Java programmers must grasp. Understand the role of the volatile keyword is to understand the premise of Java memory model, not talked about here Java memory model, you can see the first 31 points, the role of the volatile keyword two main reasons:
  • 1, multi-threaded mainly revolves around visibility and atomicity two properties, the use of the volatile keyword variables modified to ensure its visibility among multiple threads, that is, each read volatile variable, it must be the latest data
  • 2, the code underlying execution as we have seen high-level language ---- Java program so simple, its execution is Java code -> byte code -> execute bytecode corresponding C / C ++ code based on - > C / C ++ code is compiled into assembly language -> and hardware interaction, in reality, in order to obtain better performance JVM might command reordering, there may be some unexpected problems under multiple threads. Will prohibit the use of volatile semantics of reordering, of course, also to some extent reduce the efficiency of code execution from a practical standpoint, it is an important role of volatile and CAS is combined to ensure the atomicity, details can be found in java.util. under the category concurrent.atomic packages, such AtomicInteger.

13, the new T1, T2, T3 three threads, and how they are executed in order to ensure?

  • With the join method.

14, how to control the same time only 3 threads running?

  • 用 Semaphore。

15. Why use a thread pool?

  • We do not know the thread pool, then each thread must be created by new Thread (xxRunnable) .start () way and run a thread, less thread, then this will not be a problem, but the real environment so that multiple threads may open systems and procedures to achieve the best efficiency, when the number reaches a certain number of threads will run out of system CPU and memory resources, can also cause frequent collection and GC pauses, because every time a thread is created and destroyed consumes system resources, If you are creating a thread for each task this is a significant performance bottleneck. Therefore, the thread pool thread multiplexing great save system resources when the thread is no longer a time-tasking it will self-destruct, but not memory resident.

16, several common thread pool and talk about how this works.

  • What is the thread pool?
    Very simple, easy to see the name to know is equipped with a thread pool, we can give multiple threads to execute a thread pool to handle, and the concept of connection pooling, like, by maintaining a certain number of thread pool to achieve multiple threads multiplexing.
  • The benefits of the thread pool
    we do not know the thread pool, then each thread must be created by new Thread (xxRunnable) .start () way and run a thread, less thread, then this will not be a problem, but the real environment may open multiple threads so that systems and procedures to achieve the best efficiency, when the number reaches a certain number of threads will run out of system CPU and memory resources, can also cause frequent collection and GC pauses, because every time a thread is created and destroyed to consume If a thread is created for each task which is undoubtedly a significant performance bottleneck of system resources. Therefore, the thread pool thread multiplexing great save system resources when the thread is no longer a time-tasking it will self-destruct, but not memory resident.
  • Thread pool core classes
    in the java.util.concurrent package we can find the definition of the thread pool, which is our thread pool ThreadPoolExecutor core classes, first look at the main parameters of what class thread pool.
  • How to submit a thread
    as can easily define a first fixed size thread pool
    ExecutorService es = Executors.newFixedThreadPool (3);
  • Submit a thread
    es.submit (xxRunnble);
    es.execute (xxRunnble);
  • submit and execute, respectively, what difference does it?
    execute no return value, if you do not know the result of thread to use the execute method, the performance will be much better. submit returns a Future object, if you want to know the results on the use of thread submit submit, and abnormal thread it through Future's get method to capture the main thread.
  • How to close the thread pool
    es.shutdown ();
    no longer accept new tasks, tasks to perform before submitting the end and then close the thread pool.
    es.shutdownNow ();
    no longer accept new task, the task of trying to stop the pool and then close the thread pool and returns a list of all outstanding threads list.

17, thread pool threads started submit () and execute () method What is the difference?

  • execute no return value, if you do not know the result of thread to use the execute method, the performance will be much better. submit returns a Future object, if you want to know the results on the use of thread submit submit, and abnormal thread it through Future's get method to capture the main thread.

18, CyclicBarrier and CountDownLatch difference?

  • Two looks a bit like a class, are in java.util.concurrent, can be used to represent the code to run on a certain point, that the difference between the two:
  • 1, a thread to run CyclicBarrier after a certain point, the thread will stop running until all threads have reached this point, all the threads before re-run; CountDownLatch is not, a thread to run at some point after just continue to run it to a value of -1, the thread
  • 2, CyclicBarrier can only evoke a task, CountDownLatch can evoke a number of tasks
  • 3, CyclicBarrier reusable, CountDownLatch not be reused, the count value 0 is not used again on CountDownLatch

19, what is livelock, starvation, no lock, deadlock?

  • Deadlocks, live locks, barriers hunger is run blocking is active on emerging multi-threaded, if there was a thread
    of these three cases, that thread is no longer active, it can no longer be performed normally go.

  • Deadlock
    Deadlock is the worst case multiple threads, multiple threads each occupy lock each other's resources, but the other side each other to release the lock, then the absence of external intervention, these threads are processed state of suspended animation has been blocked to form a deadlock.
    For example, students grab a pen B A students, B students grab a book A classmate, two people occupy each other's things, are the other side first and then returned to his own also, so the dispute has been waiting for the other to go further but not resolved, the teacher let them know about this mutual back to each other, so that the intervention of external forces did they solve, of course, this is just an example there is no teacher they can be solved, if we find people like this computer case no outside interference or obstruction will always go on.

  • Livelock
    Livelock this concept we should be very few people have heard or understand its concept, but in multiple threads that do exist. Livelock precisely the opposite deadlock, deadlock is that we can not get the resources are occupied by each other's resources, and the resources to get the live lock is released each other but do not perform. When multiple threads appeared mutual accommodation, they offered to release resources to other threads, so the beating and the lack of resources between multiple execution threads, this is the live lock.

  • Hunger
    We know that multi-threaded execution has thread priorities this thing, higher priority threads can jump the queue and takes precedence, so that if a high-priority thread has been preempted resources low priority thread, resulting in low-priority thread can not be implemented, this is the hunger. Of course, there is a situation of hunger, a thread has been occupied and hold a resource which led to lack of implementation of the other threads, and a deadlock different hunger within the next period of time or can be performed, such as threads that take up resources ended and the release of resources.

  • No lock
    no lock, that is no lock on the resource that all threads can access and modify the same resources, but at the same time only one thread can be modified successfully. No lock typical feature is a modification operation within a loop, the thread will continue to try to modify a shared resource, if there is no conflict on the amendment and successfully quit or it will try to continue to the next cycle. So, if there are multiple threads to modify the same value are bound to be modified a thread can succeed while others fail to modify the thread will keep retrying until modified successfully. Previous article I introduced CAS principle and application of the JDK that is lock-free implementation.
    As can be seen, no lock is a very good design, it will not jump with a thread, the lock is certainly improper use of system performance issues occur, although there is no lock can not fully replace the locks, but no lock in some under the occasion it is very efficient.

20, what is the atomicity, visibility, orderly?

  • Atomicity, visibility, ordering is multi-threaded programming in several of the most important knowledge point, due to the complexity of multithreading, each thread can see how to make the correct result, which is very important.

  • Atomicity
    Atomicity refers to a thread operation can not be interrupted by other threads, at the same time only one thread operates on a variable. In the case of multiple threads, each thread of execution results without interference from other threads, such as multiple threads at the same time on the same shared member variable n ++ 100 times, the initial value is 0 if n, n should be the last value 100, so that they interfere with each other, this is the legendary atomicity in. N ++ but not the atomic operation to guarantee the atomicity AtomicInteger use.

  • Visibility
    Visibility refers to a thread changes the value of a variable of a shared, while other threads can see whether the value of the shared variable modification. Would not have this problem in the single-threaded, single-threaded read definitely are the latest values, and in multi-threaded programming might not be.
    Each thread has its own working memory, threads first shared values of variables read from the main memory, working memory, a copy of the form, when the value is calculated after a copy of the brush and then back to main memory, from reading to the last brush back main memory this is a process, not when the brush back to main memory when this time to other threads are not visible, so the other threads read from main memory value is the old value before modification. Like the CPU cache optimization, hardware optimization, the instruction rearrangement and optimization JVM compiler, there will be visibility problems.

  • Orderliness
    We all know that the program is executed by order of the code, it is indeed the case for single-threaded, multi-threaded but in case it is not the case. In order to optimize and improve the processing performance of the program execution of the CPU, JVM, and operating system instructions are rearranged, the previous code is to say in front of the code will not necessarily perform the back, i.e. behind the code may be inserted in front of the code prior to execution, it does not affect the current thread of execution results. Therefore, the instruction rearrangement will ensure consistent implementation of the results of the current thread, but the instruction rearrangement is bound to affect the results of multiple threads. Although reordering optimizes performance, but will also follow some rules, and not just the sort of chaos, just reordering affect the outcome of the implementation of multi-threading.

  • What is a daemon thread?
    The daemon thread corresponding to that user threads, thread a daemon thread is to safeguard the user, when the user executing the thread all over, the guardian will follow the end of the thread. That is, the user daemon thread must be accompanied by a thread, if there is only one application within a daemon thread, there is no user thread, the thread will naturally guard exits.

22, the exception will occur how a thread running?

  • If the exception is not caught the thread will stop executing. Thread.UncaughtExceptionHandler for handling uncaught exceptions caused by a sudden interruption of a thread-line interface. When an uncaught exception will cause disruption JVM thread will use Thread.getUncaughtExceptionHandler () to query the thread and the thread UncaughtExceptionHandler and abnormal passed as parameters to the uncaughtException handler () method for processing.

23, a thread yield () method What is the use?

  • Yield method to pause the currently executing thread object, let the other have the same priority thread. It is a static method and only guarantee the current thread can not give up CPU usage to ensure that other threads will be able to take up the CPU, execute yield () thread is likely to be executed immediately after entering the suspended state.

24, what is reentrant lock?

  • The so-called re-entry lock, are defined by a thread as a unit, when a thread gets target lock, the thread can acquire the lock on this object again, while the other thread is not.

25, Synchronized, which has several uses?

  • Lock, the lock method, a lock block.

26, Fork / Join framework is doing?

  • Big task automatically dispersed small tasks, concurrent execution, results with small tasks.

27, the number of threads will cause too much anything unusual?

  • Thread too much will cause stack overflow, it may cause abnormal heap.

28, to talk about a collection of thread-safe and unsafe.

  • Java, usually the most used Map HashMap is a collection, and it is thread safe.
  • Look at the following two scenarios:
  • 1, when the local variables used in the method of local variables belonging to the current thread-level variables, other threads can not access, so when there is no thread-safe insecurity problem.
  • 2, when used in singleton object member variables of time for it? This time over multiple threads access a HashMap is the same, and this time there is a thread safety problem with a HashMap of operation.

29. What is CAS algorithm? What applications in multiple threads.

  • CAS, called the Compare and Swap, namely comparison - replaced. Suppose there are three operands: Memory value V, the expected value of the old A, B values ​​to be modified, if and only if the expected value of the A and V are the same memory value, the memory value will be revised to B and returns true, what else nothing and returns false. Of course, with the CAS variable must be volatile, so as to ensure that each variable is the main memory to get the latest that value, otherwise the old expectations A thread on a post, it is always a value of A will not change, as long as CAS a particular operation fails, it will never succeed. Application of Algorithm java.util.concurrent.atomic package Atom **** class has the following CAS.

30, how to detect whether a thread has a lock?

  • java.lang.Thread#holdsLock 方法

31, Jdk multithreading issues in the investigation what order?

  • jstack

32, thread synchronization needs attention?

  • 1, to minimize the scope of synchronization, increase system throughput.
  • 2, distributed synchronization lock meaningless, to use the distributed lock.
  • 3, to prevent deadlock, attention locked sequence.

33, the thread wait () method uses what premise?

  • To use the sync blocks.

34, Fork / Join framework uses what must pay attention to?

  • If the task of dismantling the deep accumulation of the number of threads in the system, resulting in severe performance degradation of system performance;
  • If the call stack function deep, may lead to stack memory overflow;

35, how to pass data between threads?

  • By sharing objects between threads on it, and then wait / notify / notifyAll, await / signal / signalAll be arouse and wait, say BlockingQueue blocking queue data is shared between threads and design

36, to ensure "visibility" What are the different ways?

  • synchronized 和 viotatile

37, said that several commonly used interface Lock lock.

  • ReentrantLock、ReadWriteLock

38. What ThreadLocal that? What scenario?

  • ThreadLocal role is to provide a local variable within the threads in the thread of this variable lifecycle functions, reduce the complexity of several common variables passed between a plurality of functions or components within the same thread. To resolve the database connection, Session management.

39, ReadWriteLock what's the use?

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

40. What FutureTask that?

  • FutureTask asynchronous operation represents a task, which can pass a Callable FutureTask specific implementation classes, may be the result of the asynchronous operation of the task waiting to acquire, if the determination has been completed, to cancel the operation tasks.

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

42, immutable objects was going to help multithreading?

  • Immutable object to ensure visibility of the memory object, read immutable object does not require additional means of synchronization, mention
    lift code efficiency.

43, multi-thread context switching What does it mean?

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

44, Java used in what thread scheduling algorithm?

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

45. What is the role Thread.sleep (0) is?

  • Since Java preemptive thread scheduling algorithm, so there may be a case of threads often get into control of the CPU, in order to allow some low priority threads can get to the control of the CPU, you can use Thread.sleep ( 0) triggered manually operated once the operating system allocation of time slices, which is the balance of operating control of the CPU.

46, what is the optimistic and pessimistic locking?

  • Optimistic locking: 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 - replace these two actions as an atomic operation attempts to modify variables in memory, if said conflict fails, then there should be a corresponding retry logic.
  • 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.

47, Hashtable's size () method Why do sync?

  • There can be only one time synchronization method of a class fixed thread execution, but for asynchronous method of the class, you can access multiple threads simultaneously. So, this way there will be problems, may add data execution thread A Hashtable's put method, thread B you can call normal size () method to read the number of the current element of the Hashtable, to read that value may not be current , a thread may be added over the data, but there is no size ++, thread B has read size, then thread B is for reading a certain size to be inaccurate. And to the size () method after the addition of synchronous, meaning that thread B calls the size () method can be called only after a call to put the thread A method is completed, thus ensuring the security thread CPU executing code, not Java code execution, this is key, you have to remember. Java code will eventually be translated into machine code is the real code that can execute machine code and hardware interaction. Even if you see only a single line of Java code, you see that even after the bytecode generated Java code is compiled, only one line, it does not mean that the underlying operating for only one sentence statement. A "return count" hypothesis has been translated into three assembler statement is executed, a compilation of statements and its machine code corresponding to do, and there could complete the implementation of the first sentence, the thread switched.

48, synchronization method and synchronized block, which is better?

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

49. What is the spin lock?

  • Make use of spin locks are kept in the current thread of execution to achieve body circulation, when the loop condition is changed by other threads
    to enter the critical section.

50, Runnable and Thread with which good?

  • Java does not support multiple inheritance class, but allow you to implement multiple interfaces. So if you want to inherit from other classes, but also to reduce
    the coupling between the small class, Runnable will be better.

51, Java in notify and notifyAll What is the difference?

  • notify () method can not wake up a specific thread, so only one thread it have handy while waiting. The notifyAll () wakes up all the threads and allows them to compete for locks to ensure that there is at least one thread can continue to run.

52, why wait / notify / notifyAll these methods are not thread inside the class?

  • This is a design-related issue, it is a study of the interviewer think about the current system and some common but it seems irrational things. Answer these questions, you have to explain why these methods on the Object class is meaningful, and not put it in the Thread class reasons. One obvious reason is that the lock is JAVA provide object-level and not the thread level, each object has a lock obtained by a thread. If a thread needs to wait for some lock then call the object wait () method to sense. If the wait () method defined in the Thread class, which thread is waiting for the lock is not obvious. Simply put, because the wait, notify and notifyAll are lock-level operations, so they are defined in the Object class because locks belong to the object.

53, why wait and notify methods to be invoked in a synchronized block?

  • Mainly because the Java API forced to do so, if you do not, your code will throw an exception IllegalMonitorStateException. Another reason is to avoid race conditions between the wait and notify.

54, why you should check in a loop waiting for the conditions?

  • Thread in a wait state may receive false alarms and spurious wake, if not wait for the cycle to check the conditions, the program will not meet in the case of the end of the exit conditions. Therefore, when a waiting thread wakes up, it can not be considered the original waiting status is still valid, after the method call and notify waiting threads wake up before this time it may change (). This is the use of wait in a loop () method better reason, you can create a template call wait and notify a try in Eclipse.

55, Java heap and stack What is the difference?

  • Each thread has its own stack memory for storing local variables, method parameters and the call stack, variables stored in a thread on the other thread is not visible. The heap is shared by all threads in a public area of ​​memory. Objects are created on the heap, in order to enhance the efficiency of thread will get from a heap cache to its own stack, it could cause problems if multiple threads use the variable, then the volatile variables come into play, and it requires from the main thread reading stored values ​​of the variables.

56, how do you get the thread stack in Java?

  • For different operating systems, there are several ways to obtain the thread stack Java process. When you get the thread stack, JVM will save the state of all threads to a log file or to the console. In Windows you can use Ctrl + Break key combination to obtain the thread stack, Linux under a kill -3 command. You can also use this tool to get jstack, it operates thread id, id with jps you can find this tool.

57, how to create a thread-safe singleton pattern?

  • I.e. a JVM singleton pattern exists only in memory object instance of a class classification
  • 1, lazy type
    when you create an instance of the class loader
  • 2, hungry Chinese-style
    use when it creates an instance

58, what is blocking method?

  • Blocking method means that the program will wait until the process is completed do not do other things during, ServerSocket's accept () method that has been waiting for client connections. Here is the obstruction before the call returns, the current thread is suspended, it will not return until after the results. In addition, asynchronous and non-blocking method returns before the task is completed.

59, made what raw thread pool when the queue is full will be submitted to the task?

  • It will refuse to execute strategies When the number of threads in the thread pool is less than the maximum number of maximumPoolSize creates a new thread to handle, while the number of threads in the thread pool greater than equal to the maximum number of maximumPoolSize.

Guess you like

Origin blog.51cto.com/14570694/2469697