(reprinted and collated from the concurrent programming network, slightly modified to organize, more to explore and share, learn together, we are willing to become an offer harvester!) )
Multithreading and concurrency issues are among the questions that interviewers prefer to ask in a Java technology interview. Here, the interview from the perspective of the most important issues listed, but you should still have a solid grasp of the Java Multi-threaded basic knowledge to meet the future problems!
Java Multithreading interview question 1. What is the difference between a process and a thread?
System to do one thing, run a task, this task is a program, each running program is a process, when a program runs, the interior contains multiple sequential execution flow, each sequential execution flow is a thread. The Java Runtime environment is a single process that contains different classes and programs. Threads can be called lightweight processes. Threads require fewer resources to create and reside in a process, and can share resources in a process.
2. What are the benefits of multithreaded programming?
In multithreaded programs, multiple threads are executed concurrently to raise Gao Cheng efficiency , and the CPU does not go idle because a thread needs to wait for resources. Multiple threads share heap memory , so creating multiple threads to perform some tasks is better than creating multiple processes. For example, a servlet is more efficient than CGI because the servlet supports multithreading and CGI does not support it.
3.What is the difference between a user thread and a daemon thread??
when we create a thread in a Java program, it is called a user thread, and the JVM cannot shut down when there is a user thread running. A daemon thread is a thread that executes in the background and does not prevent the JVM from terminating. When no user thread is running, there is no user thread, and the JVM shuts down the program and exits. A daemon thread creates a child thread that is still a daemon thread .
4. How do we create a thread?
There are two ways to create a thread: one is to implement the Runnable interface, then pass it to the constructor of thread, create a thread object, and inherit the thread class directly.
5. What are the different thread lifecycles?
When we create a new thread in a Java program, its state is new (new). When we call the thread's start () method, the state is changed to runnable (ready). The thread scheduler allocates CPU time to threads in the Runnable thread pool and says their state changes to running (run). Other thread states also have waiting (wait), Blocked (blocking), and dead (death).
6. Can I call the run () method of the thread class directly?
Sure, but if we call the thread's run () method, it behaves like a normal method, and in order to execute our code in a new thread, the Thread.Start () method must be used.
7. How do I get a running thread to pause for a while?
We can use the sleep () method of the thread class to suspend a thread for a while. It is important to note that this does not cause the thread to terminate, and once the thread is awakened from hibernation, the state of the thread will be changed to Runnable, and it will be executed according to the thread dispatch.
8. What is your understanding of thread priorities?
Each thread has a priority, in general, a high-priority thread will have precedence at run time, but this depends on the implementation of the thread schedule, which is related to the operating system. We can define the priority of threads, but this does not guarantee that high-priority threads will be executed before the low-priority thread. The thread priority is an int variable (from 1-10), 1 represents the lowest priority, and 10 represents the highest priority.
9. What is thread Scheduler (threads Scheduler) and time slicing?
The thread scheduler is an operating system service that is responsible for allocating CPU time to threads in the runnable (Ready) state. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. time sharding refers to the process of allocating available CPU time to available Runnable threads . The allocated CPU time can be based on the thread priority or the time the thread waits . Thread scheduling is not controlled by the Java Virtual machine, so it is better to control it by the application (i.e. don't let your program depend on the priority of the thread).
10. What is context switching (context-switching) in multi-threading?
Context switching is the process of saving and recovering CPU state, which enables thread execution to resume execution from a breakpoint. Context switching is a fundamental feature of multitasking operating systems and multithreaded environments.
11. How do you make sure that the thread on which the main () method resides is the last thread that the Java program ends?
We can use the join () method of the thread class to ensure that all program-created threads end before the main () method exits.
12.How are the threads communicating?
When resources are shared between threads, inter-thread communication is an important means of reconciling them. The Wait (), notify (), Notifyall () methods in the object class can be used to communicate between threads about the state of a lock on a resource .
13. Why is the thread communication method Wait (),, notify (), and notifyall () defined in the object class?
Every object in Java has a lock (monitor, which can also be a monitor) and wait (), notify (), and so on to wait for the object's lock or to notify other thread objects that the monitor is available. There are no locks and synchronizers available for any object in Java threads. This is why these methods are part of the object class, so that every class in Java has a basic method for inter-thread communication.
14. Why wait (), notify (), and Notifyall () must be called in the synchronization method or in the synchronization block?
When a thread needs to invoke the object's Wait () method, the thread must have a lock on the object, and then it will release the object lock and enter the wait state until the other thread calls the Notify () method on the object . Similarly, when a thread needs to invoke the object's notify () method, it releases the lock on the object so that other waiting threads can get the object lock. since all of these methods require a thread to hold the lock on the object, this can only be done by synchronization, so they can only be called in a synchronous method or in a synchronous block.
15. Why is the sleep () and yield () method of the thread class static?
The sleep () and yield () methods of the thread class will run on the currently executing thread. So it makes no sense to raise these methods on other waiting threads. That's why these methods are static . They can work in the currently executing thread and prevent programmers from mistakenly thinking that these methods can be called on other non-running threads.
16. How to ensure thread safety?
There are many ways to ensure thread safety in Java-synchronization, using atomic classes, implementing concurrent locks, using the volatile keyword, and using immutable classes and thread-safe classes.
How does the volatile keyword work in Java?
When we use the volatile keyword to modify a variable, the thread will read the variable directly and not cache it. This ensures that the variables read by the thread are consistent with the memory .
18. What is the better choice for synchronous and synchronous blocks?
synchronizing a block is a better choice because it does not lock the entire object (you can, of course, lock the entire object). The synchronization method locks the entire object, even if there are multiple unrelated synchronization blocks in the class, which usually causes them to stop executing and to wait for a lock on the object.
19. How do I create a daemon thread?
Using the Setdaemon (true) method of the thread class to set the thread as the daemon thread, it is important to note that this method needs to be called before the start () method is called, or the illegalthreadstateexception exception will be thrown.
20. What is Threadlocal?
Threadlocal is used to create local variables for threads, we know that all threads of an object share its global variables, so these variables are not thread-safe and we can use synchronous technology. But when we don't want to use synchronization, we can choose the threadlocal variable.
Each thread will have their own thread variable, which can use the Get () \set () method to get their default values or change their values inside the thread. Threadlocal instances are typically the private static property that you want them to associate with the thread state.
21. What is the thread Group? Why is it recommended to use it?
Threadgroup is a class whose purpose is to provide information about thread groups.
The Threadgroup API is weak, and it does not provide more functionality than thread. It has two main functions: one is to get the list of active threads in the thread group, and the other is to set the uncaught exception handler (Ncaught exception handler) to the thread setting. But in Java 1.5 The thread class also added the setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) method, so Threadgroup is obsolete, Continued use is not recommended.
1 |
t1.setUncaughtExceptionHandler( new UncaughtExceptionHandler(){ |
4 |
public void uncaughtException(Thread t, Throwable e) { |
5 |
System.out.println( "exception occured:" +e.getMessage()); |
22. What is a Java thread dump (thread dump) and how do I get it?
A thread dump is a list of JVM active threads, which is useful for parsing system bottlenecks and deadlocks. There are many ways to get a thread dump--using the profiler,kill-3 command, Jstack tools, and so on. I prefer the Jstack tool because it is easy to use and comes with a JDK. Since it is a terminal-based tool, we can write some scripts to generate thread dumps periodically for analysis.
23. What is a deadlock (Deadlock)? How do I analyze and avoid deadlocks?
Deadlocks are situations in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.
Parsing deadlocks, we need to look at thread dumps for Java applications. We need to identify the threads that are blocked and the resources they wait for. Each resource has a unique ID, which we can use to find out which threads already have their object locks.
Avoiding nested locks, using locks only where needed and avoiding waiting indefinitely is the usual way to avoid deadlocks.
Java.util.Timer is a tool class that can be used to schedule a thread to execute at a specific time in the future. The timer class can be used to schedule one-time tasks or periodic tasks.
Java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to inherit the class to create our own timed task and use the timer to schedule its execution.
25. What is a thread pool? How do I create a Java thread pool?
A thread pool manages a set of worker threads, and It also includes a queue that is used to place tasks that are waiting to be executed .
Java.util.concurrent.Executors provides an implementation of the Java.util.concurrent.Executor interface for creating a thread pool.
Java concurrency interview question 1. What is atomic manipulation? What are the atomic classes (atomic classes) in the Java Concurrency API?
An atomic operation is an operation task unit that is not affected by other operations. Atomic manipulation is a necessary means of avoiding data inconsistency in a multithreaded environment.
Int++ is not an atomic operation, so when one thread reads its value and adds 1 o'clock, another thread may read the previous value, which raises an error.
In order to solve this problem, it is necessary to ensure that the increment operation is atomic, and we can use synchronous technology to do this before JDK1.5. To the Jdk1.5,java.util.concurrent.atomic package provides an int and a long type of class, which can be automatically guaranteed to be atomic for their operations and do not require synchronous use.
2. What is the lock interface (lock interface) in the Java Concurrency API? What are the advantages of comparing synchronization?
The lock interface provides a more scalable lock operation than synchronous methods and synchronization blocks. They allow more flexible structures, can have completely different properties, and can support multiple related classes of conditional objects.
It has the following advantages:
- Can make the lock more fair
- Allows threads to respond to interrupts while waiting for a lock
- Allows a thread to attempt to acquire a lock and return immediately or wait for a period of time when the lock cannot be acquired
- Locks can be acquired and released in different order in different ranges
3. What is the executors framework?
The Executor framework is introduced in Java 5 with the Java.util.concurrent.Executor interface. The executor framework is a framework for invoking, dispatching, executing, and controlling asynchronous tasks based on a set of execution policies.
Unlimited creation of threads can cause application memory overflow. So creating a thread pool is a better solution because you can limit the number of threads and recycle those threads. The executors framework makes it very easy to create a thread pool.
4. What is a blocking queue? How do I use a blocking queue to implement a producer-consumer model?
The Java.util.concurrent.BlockingQueue feature is that when the queue is empty, the operation to get or delete elements from the queue is blocked, or when the queue is full, the operation to add elements to the queue is blocked.
The blocking queue does not accept null values, and when you try to add null values to the queue, it throws nullpointerexception.
The implementation of the blocking queue is thread-safe, and all query methods are atomic and use internal locks or other forms of concurrency control.
The Blockingqueue interface is part of the Java Collections Framework and is primarily used to implement producer-consumer issues.
5. What is callable and future?
Java 5 introduces the Java.util.concurrent.Callable interface in the concurrency package, which is similar to the Runnable interface, but it can return an object or throw an exception.
The callable interface uses generics to define its return type. The Executors class provides some useful ways to perform tasks within a callable in a thread pool. Since the callable task is parallel, we must wait for it to return the result. The Java.util.concurrent.Future object solves this problem for us. After the online pool submits the callable task, a future object is returned, using which we can know the status of the callable task and get the result of the execution callable returned. The future provides a get () method so that we can wait for callable to end and get its execution results.
6. What is Futuretask?
Futuretask is a fundamental implementation of the future, and we can use it with executors to handle asynchronous tasks. Usually we do not need to use the Futuretask class, it becomes very useful when we intend to rewrite some methods of the future interface and keep the original base implementation. We can just inherit from it and rewrite the methods we need.
7. What is the implementation of concurrent containers?
Java collection classes are fast failures, which means that when a collection is changed and a thread iterates through the collection using Iterators, the next () method of the iterator throws a Concurrentmodificationexception exception.
Concurrent containers support concurrent traversal and concurrent updates.
The main classes are Concurrenthashmap, Copyonwritearraylist and Copyonwritearrayset.
8. What is the Executors class?
Executors provides some tool methods for the Executor,executorservice,scheduledexecutorservice,threadfactory and callable classes.
Executors can be used to create a thread pool conveniently.
Interview questions: Multithreading