Java basic interview questions and answers (c)

Multithreading

35. The parallel and concurrent What is the difference?

  • Parallel means that two or more events occur at the same time; and refers to two or more concurrent events occur at the same time intervals.

  • Parallel multiple events on different entities, concurrent multiple events on the same entity.

  • On a single processor "simultaneous" process multiple tasks simultaneously process multiple tasks across multiple processor. As hadoop distributed cluster.

Therefore, concurrent programming goal is to fully utilize every core processors to achieve the highest processing performance.

 

36. The difference between threads and processes?

In short, the process is the basic unit program is running and resource allocation, a program has at least one process, a process has at least one thread. During execution process has a separate memory unit, and multiple threads share memory resources, reduce the switching frequency and thus more efficient. A thread is a physical process, is the basic unit of cpu scheduling and dispatch, is smaller than the program of the basic unit can operate independently. You can execute concurrently across multiple threads in the same process.

 

37. What threads are the guardian?

Daemon threads (ie daemon thread), is a service thread, to be precise, it is to serve other threads.

 

38. What are the different ways to create a thread?

①. Inheritance Thread class Thread class is created

  • Subclass definition of the Thread class and override the run method of the class, method body that represents the run method of the thread to complete the task. Thus the run () method is called executable.

  • Create an instance of a subclass of Thread that created thread object.

  • Call the thread object's start () method to start the thread.

②. Create threads through the Runnable interface class

  • Runnable defined interface implementation class, interface and override the run () method, the method body run () method of the same thread of execution threads.

  • Create an instance of Runnable implementation class, and so as an example of a target to create Thread Thread object, the Thread object is the real thread object.

  • Call the thread object's start () method to start the thread.

③. Create a thread through Callable and Future

  • Create Callable interface implementation class, and implements call () method, the call () method as a thread of execution, and return values.

  • Callable create an instance of the implementation class, using packaging Callable FutureTask class object, which object encapsulates FutureTask Callable object of the call () method returns the value.

  • Use FutureTask Thread object as a target object to create and start a new thread.

  • Call FutureTask object get () method to obtain the return value after the end of the sub-thread execution.

 

Say something runnable and callable 39. What is the difference?

A little deeper problem, also see a breadth of knowledge of Java programmers to learn.

  • The return value run Runnable interface () method is void, just do it purely to perform the run () method code in it;

  • call Callable interface () method returns a value, is a generic, and Future, FutureTask can be used to obtain the results asynchronously with the execution.

 

40. What are the thread state?

Thread usually have five states, create, ready, running, blocking and death.

  • Creating state. In the generation thread object, start method of the object and does not call, this is the state of the thread is created.

  • Ready state. When the call start method of thread object, the thread into the ready state, but this time the thread scheduler does not take into the threads to the current thread, this time in a ready state. After thread running from the back after waiting or sleeping, also in a ready state.

  • Operating status. Thread sets a thread scheduler in a ready state for the current thread, then thread enters the run state, the run starts running among the function code.

  • Blocking state. When running thread, it is suspended, usually for waiting to happen at a certain time and then continue to run after (for example, a resource ready). sleep, suspend, wait thread and other methods can lead to blockage.

  • Death state. If a thread run method of execution end or stop method is called, the thread will die. For thread dead, you can no longer use the start method to make it into the ready   

 

41. sleep () and wait () What is the difference?

sleep (): method is thread class (Thread) static method, so that the calling thread to sleep, let out the implementation of the opportunity to the other thread, until the end of the sleep time, the thread into the ready state and other threads competing execution time cpu together. Because the sleep () is static static approach, he can not change the target machine lock, when a synchronized block called sleep () method, the thread though goes to sleep, but the machine lock object has not been released, the other threads still can not access this object.

wait (): wait () method of the Object class, when a thread is executed to wait method, and it proceeds to a waiting pool associated with the object, the object while releasing the lock of the machine, so that other threads can access, via notify, notifyAll method to wake up waiting threads

 

42. notify () and notifyAll () What is the difference?

  • If a thread calls the object's wait () method, the thread will be the object in a wait pool, pool thread will not wait for the competition to lock the object.

  • When there is a thread calls the object notifyAll () method (wake up all wait thread) or notify () method (random only wake a wait thread), wakes up the thread goes to lock the pool of the object, lock the pool thread lock to compete for the object. In other words, as long as the call to notify a thread waiting to enter the pool by the lock pool, and notifyAll will move all the objects within the pool threads waiting to lock the pool, waiting for the lock to compete.

  • High priority threads competing to lock the probability of large objects, if a thread is no competition to the object lock, it will stay in the lock pool, the only thread calls again wait () method, it will return to the waiting pool in. The competition subject to lock down the thread execution continues until the execution is over synchronized block of code, it will free up the object lock, then lock the thread pool will continue to compete the object lock.

 

43. The thread's run () and start () What is the difference?

Each thread is run by the process of a specific object corresponds Thread () to complete its operation, the method run () called threads thereof. To start a thread by calling start () method of the Thread class.

start () method to start a thread, truly multi-threaded operation. Then without waiting for the run method body code execution is completed, you can proceed directly to the following code; then this thread is in the ready state and is not running. Then this method calls the Thread class run () to complete its operational state, where the method run () is called thread body, which contains the contents of this thread to be executed, ending the Run method to run this thread to terminate. Then CPU rescheduling other threads.

run () method in this thread, the thread is only a function, but not multi-threaded. If the direct call to run (), in fact, the equivalent of calling a general function only, stand straight run () method must wait for the run () method is finished in order to execute the following code, it is still only one execution path, there is no thread feature, so when you want to use multiple threads of execution start () method instead of run () method.

 

44. create a thread pool, which has several ways?

①. newFixedThreadPool(int nThreads)

Thread pool that creates a fixed-length, submitted whenever a task to create a thread, until the maximum number of threads in the pool, then thread size will not change, but when the end was an unexpected error occurs when a thread, the thread pool will complement a new thread.

②. newCachedThreadPool()

Creates a cached thread pool, if the size of the thread pool exceeds the processing requirements, will automatically reclaim idle thread, and when demand increases, you can automatically add a new thread, the thread pool size of the absence of any restrictions.

③. newSingleThreadExecutor ()

This is a single-threaded Executor, it creates a single worker thread to perform the task, if the thread ends abnormally, will create a new one to replace it; it is characterized to ensure serial execution in accordance with the order of tasks in the queue.

④. newScheduledThreadPool(int corePoolSize)

It creates a fixed length of thread pool, and so as to delay or time to perform tasks similar to the Timer.

 

45. What are the thread pool status?

Thread pool has five states: Running, ShutDown, Stop, Tidying, Terminated.

Each thread pool status switch of FIG frame:

 

46. ​​The thread pool submit () and execute () method What is the difference?

  • Received parameters are not the same

  • submit returns a value, but did not execute

  • submit convenience Exception handling

 

47. In the java program how to ensure the safe operation of multi-threaded?

Thread safety is reflected in three aspects:

  • Atomicity: providing exclusive access, only one thread at a time to operate on the data, (atomic, synchronized);

  • Visibility: Modifying a thread of main memory in a timely manner can be seen by other threads, (synchronized, volatile);

  • Ordering: a thread other thread observe the order of execution, since the instruction reordering, this observation is generally disorderly, (happens-before principle).

 

48. What is the principle of multi-threaded lock upgrade is?

In Java, the lock comprises four states, the level from low to high order: no state locks, lock bias, lightweight and heavyweight lock lock state, these states will compete with the escalating situation. Lock can upgrade but can not downgrade.

Lock escalation process diagram: 

 

 

49. What is a deadlock?

Deadlock refers to two or more processes in the implementation process, due to the competition for resources or A blocking phenomenon caused due communicate with each other, without external force, they will not be able to promote it. At this time, say the system is in deadlock state or system to produce a deadlock, which is always in the process of waiting for another process called the deadlock. Is a wrong operating system level, the process is referred to as the deadlock, first proposed by Dijkstra in the study of the banker's algorithm in 1965, it is one of the problems the computer operating system and the whole field of concurrent programming difficult to deal with.

 

50. how to prevent a deadlock?

Deadlock four requirements:

  • Mutually exclusive conditions: the process of resource allocation to allow other processes to access, if other processes to access the resource, can only wait until after the release of the resource in possession of the resources used by the process is completed

  • Request and keeping conditions: after the process of obtaining some resources, but also makes a request for additional resources, but the resources may be occupied by another process, the matter blocking request, but was kept on hold its own resources

  • Inalienable condition: refers to the process of resources acquired before using unfinished, inalienable, our only released after use

  • Loop wait condition: it refers to the process deadlock, the circle of contact formed between a plurality of processes waiting for a resource end to end relationship

These four conditions are necessary conditions for deadlock, as long as the system deadlock, the establishment of these conditions are inevitable, but as long as one of the above conditions are not met, it will not happen deadlock.

Understand the reason for the deadlock, especially four necessary conditions for deadlock, it were possible to avoid, prevent and relieve the deadlock.

So, pay attention to in terms of system design, process scheduling, how to keep the four necessary conditions are met, how to determine a reasonable resource allocation algorithm, to avoid the process of permanently occupied system resources.

Moreover, we have to prevent the process consumes resources without a wait state. Therefore, the allocation of resources should be given a reasonable plan.


51. ThreadLocal What is that? What are the usage scenarios?

Thread-local variables are variables limited internal thread, all belonging to the thread itself, among a plurality of threads are not shared. ThreadLocal Java provides classes for thread-local variables, it is a way to achieve thread-safe. However, under the management of the environment (such as a web server) using thread-local variables of time to be especially careful, in this case, the worker's life cycle longer than the life cycle of any application variables. Once any thread local variables is not released after the work is completed, Java applications, there is a risk of memory leaks.

 

52. talk about synchronized to achieve the underlying principle?

or a method can ensure that synchronized code block during operation, that only one way to enter the critical region, while it can guarantee the visibility of memory shared variables.

Each object in Java can be used as a lock, which is synchronized to achieve synchronization of the foundation:

  • Common synchronization method, the lock is the current instance of the object

  • Static synchronized method, the object lock is the class of the current class

  • Block synchronization method, the object lock is inside the brackets


What is the difference 53. synchronized and volatile that?

  • volatile nature is telling jvm current variable values ​​in register (working memory) is uncertain, needs to be read from the main memory; synchronized current variable is locked, only the current thread can access the variables, other threads are blocked live .

  • volatile level can only be used in a variable; the synchronized variables can be used in the methods, and the class level.

  • volatile visibility can be achieved only modify variables, it does not guarantee atomicity; synchronized and modifications can ensure visibility and atomic variables.

  • volatile will not cause obstruction thread; synchronized may cause obstruction thread.

  • Variable volatile flag will not be optimized compiler; mark may be synchronized variable optimizing compiler.

 

54. synchronized and Lock What is the difference?

  • First synchronized keyword is java built in jvm level, Lock is a java class;

  • synchronized unable to determine whether to acquire the lock state, Lock can determine whether to acquire the lock;

  • synchronized automatically releases the lock (a thread after executing synchronization code will release the lock; abnormal release a lock occurs during b-threaded execution), Lock need to manually release the lock (unlock () method to release the lock) in finally in, or likely to cause the thread to die lock;

  • Synchronized keyword with two threads 1 and thread 2, 1 if the current thread to acquire the lock, thread 2 thread waiting. If blocked thread 1, thread 2 will wait forever, while Lock locks will not necessarily wait any longer, get less than if you try to lock up the thread can not wait is over;

  • synchronized reentrant locks, can not be interrupted, unfair, and Lock reentrant lock can be determined, be fair (both available);

  • Lock locks suitable for mass synchronization synchronization code, synchronized lock for a small amount of code synchronization issues.

 

55. synchronized and ReentrantLock What is the difference?

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: 

  • ReentrantLock can be set to acquire the lock wait time, thus avoiding deadlock 

  • ReentrantLock can obtain information on the various locks

  • ReentrantLock flexibility to achieve multi-channel notification 

In addition, both the lock mechanism is actually not the same: ReentrantLock underlying method call is the park's Unsafe locking, synchronized operation should be the subject header mark word.


56. talk about atomic principle?

Class basic features Atomic packet is in a multithreaded environment, when a plurality of threads simultaneously on a single (basic types and include reference type) variable operation, exclusive, i.e., when the value of the plurality of threads simultaneously variable when updating, only one thread can be successful, but not successful spin thread can lock the same to keep trying, until successful.

Atomic series of classes in core methods will call several local methods unsafe class. We need to know a thing is Unsafe class, full name: sun.misc.Unsafe, this class contains a large number of operations on the C code, including many direct memory allocation and call atomic operations, and it is the reason why non-marking safety, is to tell you a lot of ways inside this call will be a security risk, need to be used with care, otherwise it will lead to serious consequences, such as the time by unsafe allocated memory, if they specify certain areas could lead to something like C ++ as cross-border issues pointer to other processes.

Guess you like

Origin www.cnblogs.com/donleo123/p/11621036.html