Java multi-threading and concurrency basis of the interview summary

A, the Java Multithreading Interview Questions

1. What is the difference between processes and threads?

A process is an independent (self contained) operating environment, it can be seen as a program or an application. The thread is a task carried out in the process. Java runtime environment is a single process contains different classes and programs. Threads can be called lightweight processes. Thread requires fewer resources to create and resides in the process, and the process can be shared resources.

2. What are the benefits of multi-threaded programming?

In a multithreaded program, concurrent execution of multiple threads is to improve the efficiency of the program, CPU will not need to wait for a thread to enter an idle state resources. Multiple threads shared heap memory (heap memory), so creating multiple threads to perform some tasks better than creating multiple processes. For example, Servlets better than CGI, because Servlets and CGI does not support multi-threading support.

3, the user thread and thread guard what is the difference?

When we create a thread in a Java program, it is called a user thread. A thread is a daemon in the background and does not prevent the termination of the JVM thread. When there is no user threads running, JVM close the program and exit. A guardian of the child thread thread creation is still a daemon thread.

4. How do we create a thread?

There are two common ways to create a thread: one is to achieve Runnable interface, and then it passed to the Thread constructor, create a Thread object; the second is the direct successor Thread class.

5. What are the different threads of the life cycle?

When we create a new thread in a Java program, its status is New. When we call the thread's start () method, the status is changed to Runnable. Thread scheduler allocates CPU time Runnable threads in the thread pool and change their state Running.

6, can be called directly run Thread class () method it?

Of course you can, but if we call the Thread's run () method, its behavior will be the same as ordinary methods, in order to execute our code in a new thread, you must use Thread.start () method.

7, how to make a running thread pause for some time?

We can use the Thread class Sleep () method thread to pause for some time. Note that this does not make the thread terminates, the thread once awakened from hibernation, the state of the thread will be changed to Runnable, and according to thread scheduling, it will be implemented.

8. What is your understanding of thread priority is?

Each thread has a priority, in general, high priority threads at runtime has priority, but this depends on the implementation of thread scheduling, and this implementation is operating system dependent (OS dependent). We can define the priority of the thread, but this does not guarantee high-priority thread will be executed before lower priority thread. Thread priority is an int variable (from 1-10), where 1 is the lowest priority and 10 is the highest priority.

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

10, in the multi-thread, what is the context switch (context-switching)?

Context switch is to store and restore the CPU state process, so that it can be a thread of execution resumes from the interruption point. Context switching is an essential feature of multi-tasking operating systems and multi-threaded environments.

11. How do you ensure that the main () method where the thread is a Java program ended last thread?

We can use the join () method of the Thread class to ensure that all programs created by a thread before the end of main () method exits.

12, how to communicate between threads?

When the threads can share resources, inter-thread communication is important to coordinate their means. Object class wait () \ notify () \ notifyAll () method may be used for communication between threads lock on the resource state.

13. Why thread communication method of wait (), notify () and notifyAll () is defined in the Object class?

Each object has a lock in Java (monitor, the monitor may be) and wait (), notify () method and the like waiting for a lock or notification monitor objects other threads available objects. Not available for any locks and synchronization objects used in the Java thread. This is why these methods are part of the Object class, and each class has a Java basic method for communication between threads

14, why wait (), notify () and notifyAll () must be called synchronization method or a synchronized block?

When a thread needs to call the object's wait () method, the thread must have a lock on the object, then it will release the object lock and enters a wait state until another thread calls notify on this subject () method. Similarly, when a thread needs to call the object's notify () method, which will release the lock of the object, so that other thread waiting you can get the object lock. Since all of these methods require a thread holds a lock on the object, so it can only be achieved through synchronous, so they can only be called synchronization method or a synchronized block.

15, why the Thread class sleep () and yield () method is static?

Sleep (Thread class) and yield () method will be run on the thread that is currently being executed. So call these methods on other threads in a wait state is meaningless. This is why these methods are static. They can work in threads that are currently being executed, and to avoid mistakenly believe that programmers can call these methods in other non-running thread.

16, how to ensure thread-safe?

There are many ways in Java to ensure thread safety - synchronized with atomic class (atomic concurrent classes), lock concurrency, use the volatile keyword, use the same class and thread-safe class. In the thread safety tutorial, you can learn more.

17, volatile keyword in Java in what role?

When we use the volatile keyword to modify variables, so the thread will directly read the variable and does not cache it. This ensures that the thread reads the variable is the same in memory is the same.

18, synchronization method and synchronized block, which is the better choice?

Sync block is a better choice because it does not lock the entire object (of course you can make it to lock the entire object) . Synchronization method will lock the entire object , even if this class has multiple sync blocks not associated with, which often leads them to stop execution and to wait to get a lock on this object.

19, how to create a daemon thread?

Use setDaemon Thread class (true) method can set a thread as a daemon thread, you need to pay attention to is the need to call this method before calling the start () method, otherwise it will throw an exception IllegalThreadStateException.

20. What is the ThreadLocal?

ThreadLocal thread is used to create a local variable, we know that an object of all the threads share its global variables, these variables are not thread-safe, we can use synchronous technology. But when we do not want to use sync, we can choose ThreadLocal variable.

Each thread will have their own Thread variable, they can use the get () \ set () methods to get their default value or change in value of their internal thread. ThreadLocal instance they usually want to associate with the thread state is private static properties.

21. What is the Thread Group? Why is it recommended?

ThreadGroup is a class, its purpose is to provide information about the thread group.

ThreadGroup API is relatively weak, it does not provide more functionality than Thread. It has two main functions: First, get a list of active thread group in the state of a thread; the second is to set up a thread uncaught exception handler (ncaught exception handler). But in the Thread class in Java 1.5 also adds setUncaughtExceptionHandler (UncaughtExceptionHandler eh) method, so ThreadGroup is outdated, not recommended for continued use.

t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){

@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("exception occured:"+e.getMessage());
}

});

22. What is the Java thread dump (Thread Dump), how to get it?

JVM thread dump is a list of active threads, it is very useful for analyzing system bottlenecks and deadlocks. There are many ways to get a thread dump - Using Profiler, Kill -3 command, jstack tools. I prefer jstack tool because it is easy to use and comes with the JDK. Because it is a terminal-based tool, so we can write some scripts to generate timing thread dump to be analyzed.

23. What is a deadlock (Deadlock)? How to analyze and avoid deadlocks?

Deadlock refers to the case of two or more threads block forever, this situation needs to produce at least two or more than two threads and resources.

Analysis of deadlock, we need to see a thread dump Java applications. We need to find those BLOCKED state of threads and the resources they are waiting for. Each resource has a unique id, use the id we can find out which thread has its own object lock.

Avoid nested locks, lock only where needed and avoid waiting indefinitely is the usual way to avoid deadlock.

24. What is Java Timer class? How to create a task specific time interval?

java.util.Timer is a utility class that can be used to arrange a thread execution at a specific time in the future. Timer class can schedule one-time task or periodic task.

java.util.TimerTask is an abstract class implements Runnable interface, we need to extend this class to create our own timing and use the Timer task to arrange its execution.

25, what is the thread pool? How to create a Java thread pool?

A thread pool management a set of worker threads, but it also includes a queue waiting to be executed for the task of placing.

java.util.concurrent.Executors java.util.concurrent.Executor provides an implementation of the interface used to create the thread pool. ScheduledThreadPoolExecutor thread pool examples show examples of how to create and use the thread pool, or read on to learn how to create a periodic task.

Two, Java concurrency interview questions

1. What is an atomic operation? Which atoms class (atomic classes) have in Java Concurrency API in?

Refers to an atomic operation is not otherwise affect the operation of the operation unit task. Atomic operations to avoid data inconsistency means to be in a multithreaded environment.

int ++ is not an atomic operation, so when a thread reads its value and add 1, another thread might have read previous value, which will cause an error.

To solve this problem, we must ensure that the increase operation is atomic, JDK1.5 before we can use the synchronization techniques to do this. To JDK1.5, java.util.concurrent.atomic package provides long int and wrapper types, they may be automatically guaranteed for their operation is not necessary to use atoms and synchronization.

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

3. What is Executors framework?

Executor frame with java.util.concurrent.Executor interface is incorporated in Java 5. Executor framework is a framework based on a set of asynchronous task execution policy calls, scheduling, execution and control of.

Unlimited creating a thread may cause application memory overflow. So create a thread pool is a better solution, because you can limit the number of threads and can be recycled these threads. You can very easily create a thread pool using the Executors framework.

4, what is blocking queue? Consumer model - how to achieve the producer to use a blocking queue?

Java.util.concurrent.BlockingQueue characteristics are: when the queue is empty, acquisition or remove elements from the queue operations will be blocked, or when the queue is full, add to the queue operating elements will be blocked.

Blocking queue does not accept null values, when you try to add value to the empty queue when it throws NullPointerException.

Implementations are thread-safe blocking queue, all the query methods are atomic and uses internal locks or other forms of concurrency control.

BlockingQueue interface is part of java collections framework, which is mainly used to implement the producer - consumer issues.

5. What is the Callable and Future?

Java 5 is introduced in the package concurrency java.util.concurrent.Callable interface, and the interface is similar to Runnable, but it can return an object or throw an exception.

Callable generic interface to define its return type. Executors class provides several useful methods to perform tasks within Callable in the thread pool. Since Callable tasks in parallel, we have to wait for the results it returns. java.util.concurrent.Future target for us to solve this problem. After you submit Callable tasks in a thread pool returns a Future object with which we can know the state of Callable tasks and the results obtained Callable return. Future provides the get () method so that we can wait and get it Callable end of the result.

6. What is FutureTask?

FutureTask is a basis for Future implementation, we can use it to handle asynchronous tasks with Executors. Usually we do not need to use FutureTask class, single when some of the ways we intend to rewrite the Future interfaces to achieve and maintain the original foundation is, it becomes very useful. We can only inherit from it and override the method we need.

7. What is concurrency container?

Java collection classes are fail-fast, which means that when the set is changed and a thread when using iterates over the collection, the iterator's next () method throws an exception ConcurrentModificationException.

Concurrent container supports concurrent updates and concurrent traversal.

The main class has ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet.

8. What Executors class is?

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

Executors can be used to easily create a thread pool.

Follow-up. . . . . .

 

Guess you like

Origin blog.csdn.net/MyronCham/article/details/90342679