Multi-threaded interview questions and Answers

Source: Internet
Author: User
Tags semaphore

1, the basic concept of thread, the basic state of the thread and the relationship between the state?

A thread is also called a lightweight process, which is the control flow in a single order in a process, and is the smallest unit of program execution flow. A thread consists of a thread ID, a current instruction pointer, a collection of registers, and a stack. A thread is an entity of a process , usually a process that has several threads, a basic unit that is dispatched and allocated by the system, and a thread that shares all the resources of the process with other threads in the same process.

There are five basic states of the thread: The new state, the ready state, the state of operation, the blocking state, the state of death. Relationships between states such as:


1. New state: The thread object has been created and the start () method has not been invoked on it. 2. Ready state/Operational status: When the thread is eligible to run, but the scheduler has not selected it as the state of the thread when the thread is running. When the start () method is called, the thread first enters the operational state. After the thread has run or has returned from blocking, waiting, or sleeping, it returns to the operational state. 3. Running state: The thread Scheduler selects a thread from a running pool as the current thread is in the state of the thread. This is also the only way that a thread goes into a running state. 4. Wait/block/Sleep state: This is the state at which the thread is eligible to run. In fact, this three-state combination is one, and its common denominator is that the thread is still alive, but there is no condition to run at the moment. In other words, it is operational, but if an event occurs, he may return to the operational state. 5. Death state: When the thread's run () method finishes, it is considered dead. This thread object may be alive, but it is not a separate thread. Once a thread dies, it cannot be resurrected. If you call the start () method on a dead thread, the java.lang.IllegalThreadStateException exception is thrown.

2. What are the differences between threads and processes?

(1) The process is an independent unit of system resource allocation and scheduling; a thread is an entity of a process that is the basic unit of CPU dispatch and dispatch.
(2) system resources are assigned to processes; threads are independent of resource allocation, and threads share all resources of a process with other threads in the same process.
(3) Different processes have different virtual addresses, and different threads under the same process share the same address space.

Resources that the process occupies

Resources that the thread occupies

address space  
global variable  
Open file  
 
semaphore  
account information

stack  
register  
status  

a. process is the basic unit of resource allocation, thread is cpu dispatch, or the smallest unit of program execution. In mac windows nt

b. The process has a separate address space, such as in linux under the start of a new process, the system must be assigned its own address space, set up a number of data tables to maintain its code snippets, stack segments and data segments, which is a very expensive multi-tasking way of working. While running a thread in a process, they share most of the data, use the same address space, so start a thread, switch a line Chengyuan is faster than the process operation, the cost is much smaller. Of course, threads have their own local variables and stacks (note not heaps), such as in windows beginthreadex Create a new process will be called createthread _tiddata)

    c. communication between threads is more convenient. The thread sharing data under the unified process (such as global variables, static variables), through which the communication is not only fast and convenient, of course, how to handle the synchronization and mutual exclusion of these accesses is the difficulty of writing multi-threaded program. Communication between processes can only be done through process communication .

    d. by b , you can easily get the conclusion that multiple processes are more robust than multithreaded programs. A thread dies the entire process, but in protected mode , a process that dies does not have a direct impact on another process.

    E. There is a difference between the execution of a thread and the process. Each independent thread has its own program entry, sequential execution sequence and exit of the program, but the thread cannot execute independently, must be attached to the program, and the application provides concurrency control for multiple threads

3, multithreading There are several ways to achieve, what is it?

There are two ways to implement multithreading in Java, one is to inherit the thread class directly, and the other is to implement the Runnable interface.

Create thread mode One: Inherit the thread class override the Run method
Steps:
1. Define a class to inherit the thread class
2. Override the Run method in the thread class
3, create a thread for the subclass object that directly creates the thread.
4, call the Start method to open the thread and invoke the thread's task to execute the Run method.



1, defines the class implementation runnable interface.
2, overwriting the Run method in the interface, Encapsulates the thread's task code into the Run method.
3, the thread object is created through the thread class, The subclass object of the Runnable interface is passed as a parameter to the constructor of the thread class.
4, invoking the thread object's Start method to open the thread.

1 The method of Runnable () interface can realize the separation of data service and data by multiple objects, which embodies the idea of object-oriented, and inherits Thread () class method, each object processing data is different, can not achieve data sharing;

2 using the Runnable () interface method, class out of the implementation of the Runnable () interface, you can also inherit a class, and inherit The method of the Thread () class can no longer inherit the class, because java is but inherited;

3 The advantage of inheriting the method of the Thread () class is that the code is enough to look clearer.


4, multi-threaded synchronization and mutual exclusion have several implementation methods, what is it?

Thread synchronization is a constraint relationship between threads, where one thread's execution relies on another thread's message, and waits until the message arrives when it does not get another thread's message.
Thread mutex refers to the exclusive nature of the shared process system resources when each individual thread accesses it. When there are several threads that want to use a shared resource, at most one thread is allowed to use at most, and other threads that want to use that resource must wait until the resource is freed by the resource. Thread mutexes can be seen as a special kind of thread synchronization (hereinafter referred to as synchronization).

The synchronization methods between threads can be broadly divided into two categories: User mode and kernel mode. As the name implies, kernel mode refers to the use of the system kernel object of the uniqueness of synchronization, the use of the need to switch between the kernel State and user state, and user mode is not required to switch to the kernel state, only in the user state to complete the operation.
The methods in user mode are: atomic operations (e.g. a single global variable), critical section. The methods in kernel mode are: event, semaphore, mutex.

Mutex Amount (Mutex)

The mutex is similar to the critical section, and only the line friend with the mutex has permission to access the resource, because there is only one mutex object, so it is determined that the shared resource will not be accessed by multiple threads at the same time in any case. The thread that currently occupies the resource should hand over the owning mutex after the task has been processed so that other threads can access the resource after it is acquired. The mutex is more complex than the critical section. Because using mutexes not only enables the secure sharing of resources in different threads of the same application, but also enables secure sharing of resources between threads of different applications. 

The mutex contains several operations primitives: 
CreateMutex()   Create a mutex 
OpenMutex()   Open a mutex 
ReleaseMutex()   Release Mutex amount 
WaitForMultipleObjects() Wait for mutex object 

Signal Volume (semaphores)

The

semaphore object synchronizes threads differently from the previous methods, and the signal allows multiple threads to use shared resources simultaneously, as in the operating system PV operation is the same. It indicates the maximum number of threads concurrently accessing the shared resource. It allows multiple threads to access the same resource at the same time, but needs to limit the maximum number of threads that access this resource at the same time. In createsemaphore () When creating semaphores, indicate both the maximum allowable resource count and the current available resource count. In general, the current available resource count is set to the maximum resource count, and each additional thread has access to the shared resource, and the current available resource count is reduced by 1 As long as the current available resource count is greater than 0 0 Indicates that the number of threads currently occupying the resource has reached the maximum allowable number and cannot allow other threads to enter, at which point the semaphore signal will not be emitted. After the thread has finished processing the shared resource, it should go through releasesemaphore () function adds the currently available resource count to 1

The concept of PV operation and signal volume is presented by Dutch scientist E.w.dijkstra . The semaphore s is an integer,s greater than or equals zero represents the number of resource entities available to the concurrent process, but s Less than zero indicates the number of processes that are waiting to use the shared resource.

Critical Area (Criticalsection)

An easy way to ensure that only one thread can access the data at a time. Only one thread is allowed to access the shared resource at any time. If more than one thread attempts to access the critical section at the same time, all other threads that attempt to access this critical section after one thread has entered will be suspended and continue until the thread entering the critical section leaves. When the critical section is released, other threads can continue to preempt, and in this way achieve the purpose of atomic manipulation of shared resources.

The critical section consists of two operation Primitives:
EnterCriticalSection() Enter the critical section
LeaveCriticalSection() leave the critical section

After the EnterCriticalSection() statement executes, the code will enter the critical section, and no matter what happens, it must be ensured that the matching leavecriticalsection() can be executed. Otherwise, the shared resources protected by the critical section will never be freed. Although critical section synchronization is fast, it can only be used to synchronize threads within this process and not to synchronize threads in multiple processes.


Events (event)

The event object can also maintain thread synchronization by notifying the operation. And can be implemented in different processes of thread synchronization operations.

The semaphore contains several operation Primitives: 
CreateEvent()   Create a Semaphore 
openevent()   Open an event 
SetEvent()   Reset Event 
WaitForSingleObject()  wait for an event 
WaitForMultipleObjects() wait for multiple events

WaitForMultipleObjectsfunction Prototypes: 
WaitForMultipleObjects( 
in DWORD ncount,//number of wait handles 
in CONST HANDLE *lphandles,//pointer to array of handles 
in BOOL bWaitAll,//whether to completely wait for the flag 
In DWORD dwmilliseconds//Wait Time 


ParametersncountSpecifies the number of kernel objects to wait for, and the array that holds the kernel objects isLphandlesto point to. fWaitAllto the designation of thisncountThe two wait methods for the kernel object are specified,TRUEThe function returns when all objects are notified, asFALSEit can be returned as long as any of them are notified. dwmillisecondsThe role here is with theWaitForSingleObject() are fully consistent in their role. If the wait timeout occurs, the function returnsWait_timeout.  

Events can implement thread synchronization operations in different processes, and it is easy to implement priority comparison waits for multiple threads, such as writing multipleWaitForSingleObjectto replaceWaitForMultipleObjectsThis makes programming more flexible.  

5 . What are the similarities and differences between multi-threaded synchronization and mutual exclusion, and under what circumstances are they used separately? An example is described.

Thread synchronization is a constraint relationship between threads, where one thread's execution relies on another thread's message, and waits until the message arrives when it does not get another thread's message.

Thread mutex refers to the exclusive nature of the shared process system resources when each individual thread accesses it. When there are several threads that want to use a shared resource, at most one thread is allowed to use at most, and other threads that want to use that resource must wait until the resource is freed by the resource. Thread mutexes can be seen as a special kind of thread synchronization (hereinafter referred to as synchronization).

As between a producer and multiple consumers. There is a synchronous relationship between producers and consumers, and consumers are mutually exclusive relationships.

Multi-threaded interview questions and answers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.