Multithreading common interview questions summary

1. threads and processes

Thread 
 Here's a thread refers to a thread entity during program execution. JVM allows an application concurrently executing threads. Hotspot JVM in Java threads and native operating system thread has a direct mappings. When the thread local storage, buffer allocation, synchronization objects, stack, program counter, ready, it will create an operating system native threads. Java thread end, native threads will be recycled. Operating system is responsible for scheduling all the threads, and assign them to any available CPU. When the original thread initialization is complete, it will call run Java thread () method. At the end of the thread, it releases all resources native Java threads and threads.
process
  Process is a program can be executed concurrently on computing activity in a set of data, but also the operating system the basic unit of resource allocation and scheduling.

Relations and differences between processes and procedures

① program is an ordered set of instructions, it does not have any operational meaning, it is a static concept. The process is a process of program execution on the processor, it is a dynamic concept.

② software program can be used as a long-term data exist, but there is a certain process life cycle. Program is permanent, the process is temporary.

Note: The program can be seen as a recipe, but the process is the process in accordance with recipes for cooking.

③ the process and procedures of different: processes by a program, data, and process control block is composed of three parts.

④ correspondence between the process and procedures: by repeating, a program can have multiple processes; by calling relations, a process that may include more than one program.

2. The difference between the parallel and concurrent

  • One explanation: refers to two or more parallel events occur at the same time; and refers to two or more concurrent events occur at the same time intervals.
  • Explain two: Parallel multiple events on different entities, concurrent multiple events on the same entity.
  • Explains three: on a parallel processor is "simultaneous" to handle multiple tasks, is concurrently handle multiple tasks simultaneously on multiple processors. As hadoop distributed cluster.

3. Create a way to thread

Thread class inheritance
  Essentially Thread class is to achieve an instance of Runnable interface, representing an instance of a thread. The only way to start the thread is () instance method by start Thread class. start () method is a native method, it will start a new thread, and executes run () method.
Implement Runnable.
  If your class already extends another class, you can not directly extends Thread, this time, you can achieve a Runnable Interface
ExecutorService, Callable <Class>, Future thread return value
  It returns a value tasks must implement the Callable interface similar task no return value must be Runnable interface. After performing Callable task, you can get a Future object, call the get in on the object you can get to the return of the Object Callable task, combined with the thread pool ExecutorService interfaces can be achieved legends have returned results multithreading. 
Based on the way the thread pool
  Threads and database connections These resources are an invaluable resource. So every time you need to create, destroy when not needed, can be very wasteful of resources. Then we can use caching strategy is to use thread pool.

4. way to create a thread pool

newCachedThreadPool
  You may need to create a thread pool that creates new threads, but they will reuse previously constructed threads when available. For a lot of short-term program to perform asynchronous tasks, these pools will typically improve program performance. Calls to execute will reuse previously constructed threads (if the thread is available). If an existing thread is not available, a new thread is created and added to the pool. Terminate and remove those threads that have not been used for 60 seconds from the cache. Therefore, for a long time remain idle thread pool does not use any resources.
newFixedThreadPool
  Creates a thread pool that reuses a fixed number of threads to a shared unbounded queue to run these threads. At any point, in most nThreads thread is active processing tasks. If you submit additional task when all threads are active, before you have available threads, additional tasks will wait in the queue. If during the execution before the closure due to a failure of any thread terminates, then replace it with a new thread to execute subsequent tasks (if needed). Before a thread is explicitly closed, the thread pool will always exist.
newScheduledThreadPool
  Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically. 
ScheduledExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(3); 
 scheduledThreadPool.schedule(newRunnable(){ 
 @Override 
 public void run() {
 System.out.println ( "delayed three seconds" );
 }
 }, 3, TimeUnit.SECONDS);
scheduledThreadPool.scheduleAtFixedRate(newRunnable(){ 
 @Override 
 public void run() {
 System.out.println ( "delay one second every three seconds to perform a" );
 }
 },1,3,TimeUnit.SECONDS);
newSingleThreadExecutor
  (Or when an exception occurs) Executors.newSingleThreadExecutor () returns a thread pool (this is only a thread pool thread), this thread pool thread can restart after the death of a thread to replace the original thread to continue execution! 

5. Thread life cycle (state) 

  When the thread is created and started, it is neither a start to enter the execution state, nor is it has been in a state execution. In the thread of the life cycle, it has to go through New (New), Ready (Runnable), running (Running), blocked (Blocked) and death (Dead) 5 states. Especially when after the thread starts, it can not have been "occupied" the CPU to run alone, so the need to switch between multiple CPU threads, so thread state will run several times to switch between blocking

New state (NEW)
  When the program creates a thread using the new keyword, the thread is in the new state, this time only the value assigned by the JVM memory, and initializes its member variables
Ready state (RUNNABLE)
  When a thread object to call the start () method, the thread is in the ready state. Java virtual machine call stack and program counter to create a method, waiting to be scheduled to run
Run state (RUNNING):
  Thread of execution if the thread is in the ready state to obtain a CPU, started run () method, the thread is running
Blocked (BLOCKED):
  Blocking state means that thread for some reason to give up the right to use the cpu, that is let out of the cpu timeslice, temporarily stop running. Until the thread becomes runnable (runnable) state, have a chance to get cpu timeslice to run (running) state again
state. Case of obstruction of three categories:
  Wait obstruction (o.wait-> wait column):
    O.wait thread of execution run (running) () method, JVM will thread into the wait queue (waitting queue) in.
  Synchronous blocking (lock-> lock pool)
    Thread running (running) when acquiring synchronization lock object, if the synchronization lock is occupied by another thread, the JVM will lock into the thread pool (lock pool) in.
  Other blocking (sleep / join)
    Thread running (running) is performed Thread.sleep (long ms) or t.join () method, or issue the I / O request, the JVM will set the thread is blocked. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O
    When processed, the thread can run again into the (runnable) state. 
Thread death (DEAD)
Thread will end in three ways, the end is death state.
Normal end
1. run () or call () method execution is completed, the normal end of the thread.
Abend
2. Thread a throw Exception Error or uncaught.
Stop calling
3. Direct calling the thread's stop () method to end the thread - which is usually easily lead to a deadlock, not recommended.
 

 

 6.sleep and wait difference

1. For the sleep () method, we first need to know which belongs Thread class. And wait () method, Object belongs to the class.
2. sleep () method results in a program to suspend the specified time, so that the cpu of the other threads, but his remains were monitoring state, when the specified time is up will automatically resume operation.
3. In the process of calling sleep () method, the thread will not release the object lock.
4. And when the call wait () method, the thread will give up the object lock, waiting to enter the pool waiting for a lock for this object, and only for this object call notify () method of the thread after the object lock before entering the pool ready to acquire the object lock into operation status

7.start and run difference

1. start () method to start a thread, truly multi-threaded operation. Run time without waiting for the method body code is completed, you can proceed directly to the following code.
2. Start a thread by calling start () method of the Thread class, then this thread is in the ready state and is not running.
3. The method run () is called thread body, which contains the contents to be executed this thread, the thread into the running state, which runs the run function code. Run method to finish, this thread is terminated. Then CPU rescheduling other threads.

The role of 8.volatile keyword (variable visibility, prohibit reordering)

  Java language provides a weaker synchronization mechanism, namely volatile variable used to ensure that the update notification variables to other threads. volatile variables have two characteristics, volatile variables are not cached in the processor register or to other places invisible, thus always return the most recently written values ​​when reading volatile variable.
Visibility variable
  One is to ensure that the variable is visible to all threads, where visibility means that when a thread modifies the value of a variable, then the new values ​​for the other threads can be immediately obtained.
Prohibit reordering
  volatile prohibition instruction rearrangement. More than sychronized lightweight synchronization lock when accessing a volatile variable does not perform locking operations and, therefore, does not make the execution thread is blocked, so volatile variable is a more lightweight synchronization mechanism than sychronized keyword. volatile for this scenario: a variable is shared by multiple threads, the thread directly to the variable assignment. 
  When the non-volatile read and write variables, the variables each thread memory copy start to the CPU cache. If the computer has multiple CPU, each thread can be processed on a different CPU, which means that each thread can be copied to a different CPUcache in. The declaration of a variable is volatile, JVM ensures that each read variables read from memory, CPU cache skip this step.
Applicable scene
  It should be noted that a single reading of a volatile variable / write operation can be guaranteed atomicity, such as long and double variables, but does not guarantee atomicity i ++ this operation, because in essence i ++ is a read, write two operations . May be replaced in some scenarios Synchronized. However, volatile can not completely replace Synchronized position, and only in some special scenarios, in order to apply volatile. In general, the following conditions must be met in order to ensure safe concurrent thread environment:
(1) write access to the variables do not depend on the current value (such as i ++), or a simple variable assignment (booleanflag = true).
(2) the variable is not included in the invariant with other variables, i.e., between different volatile variables, not dependent on each other. To use volatile only when the state is truly independent of other content within the program.

9. The principle of first occurrence

1, the program sequence rules. In a thread EDITORIAL code book in advance occurred in the back. Rather it should be, according to the control flow of program order, because some branched structure.

2, Volatile variable rules. On a volatile variables, to write his first occurred in the read operation.

3, the thread start rule. start Thread object () method first occurrence in this thread every movement.

4, the thread terminates rules. All operations are ahead of thread termination occurs in the detection of this thread.

5, thread break rules. Call to thread interrupt () method to the first occurrence is detected interrupt thread code interrupt event.

6, the object termination rules. Initialize an object is completed (end of line constructor) begins issued finilize () method of the first occurrence.

7, transitive. A first occurrence of B, B C occurs first, then, C. A first occurs

8, the tube locking rules. The face of lock with a lock operation after a first unlock operation occurs.

10. The method calls between processes and threads

11.java common lock

12.synchronized principle underlying implementation

What 13.synchronized and ReentrantLock difference is?

  • synchronized competition will always be waiting for a lock; ReentrantLock can try to acquire the lock and get get results
  • synchronized acquiring the lock can not set time-out; ReentrantLock can set the timeout to acquire a lock
  • synchronized fairness can not be achieved lock; ReentrantLock meet fair locks, which is to wait to get into the lock
  • and control waits synchronized wakeup binding lock object wait () and notify (), notifyAll (); ReentrantLock and control waits for a wakeup Condition binding the await () and signal (), signalAll () method
  • synchronized JVM level is achieved; ReentrantLock JDK is the code level to achieve
  • executing the synchronized block of code in the lock or abnormal, automatically release the lock; of ReentrantLock not automatically release the lock, it is necessary finally {} block shows the release

14.ReentrantReadWriteLock read-write lock Detailed

Implementation 15.BlockingQueue blocking queue

 

Guess you like

Origin www.cnblogs.com/yjc1605961523/p/12594379.html