Java multithreading and concurrent basic interview summary, java Multithreading

Source: Internet
Author: User

Java multithreading and concurrent basic interview summary, java Multithreading

Multithreading and concurrency are one of the questions that the interviewer prefers to ask during the Java technical interview. Here, most important questions are listed from the interview perspective, but you should still master the basic knowledge of Java multithreading to match the problems encountered in the future. I hope to help my friends who are looking for a job.

Java multi-thread interview questions

1. What is the difference between processes and threads?

A process is an independent (self contained) running environment, which can be considered as a program or an application. A thread is a task executed in the process. A Java Runtime Environment is a single process that contains different classes and programs. A thread can be called a lightweight process. Threads require less resources to create and reside in the process, and can share resources in the process.

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

In multi-threaded programs, multiple threads are concurrently executed to improve program efficiency. The CPU does not enter idle state because a thread needs to wait for resources. Multiple threads share heap memory. Therefore, it is better to create multiple threads to execute some tasks than to create multiple processes. For example, Servlets is better than CGI because Servlets supports multithreading and CGI does not.

3. What is the difference between the user line and the daemon thread?

When we create a thread in a Java program, it is called a user thread. A daemon thread is executed in the background and does not stop JVM termination. When no user thread is running, the JVM closes the program and exits. The sub-thread created by a daemon thread 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, and then pass it to the Thread constructor to create a Thread object; the other is to directly inherit the Thread class.

5. What are the different thread lifecycles?

When we create a New thread in a Java program, its status is New. When we call the start () method of the thread, the state is changed to Runnable. The thread scheduler allocates CPU time for the threads in the Runnable thread pool and changes their status to Running.

6. Can I directly call the run () method of the Thread class?

Of course. But if we call the Thread's run () method, it will behave like a normal method. In order to execute our code in a new Thread, thread is required. start () method.

7. How to pause a running thread for a period of time?

We can use the Sleep () method of the Thread class to pause the Thread for a period of time. It should be noted that this does not cause the thread to terminate. Once the thread is awakened from sleep, the thread state will be changed to Runnable and will be executed according to thread scheduling.

8. What do you understand the thread priority?

Every thread has a priority. Generally, a thread with a higher priority has a priority at runtime, but this depends on the implementation of thread scheduling, this implementation is related to the Operating System (OS dependent ). We can define the thread priority, but this does not ensure that high-priority threads will be executed before low-priority threads. The thread priority is an int variable (from 1 to 10). 1 indicates the lowest priority, and 10 indicates the highest priority.

9. What are Thread schedulers and Time Slicing )?

The thread scheduler is an operating system service that allocates CPU time for Runnable threads. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler.

Time slice refers to the process of allocating available CPU time to available Runnable threads. The CPU allocation time can be based on the thread priority or thread wait time. Thread Scheduling is not controlled by Java virtual machines, so it is a better choice for applications to control it (that is, do not let your program depend on the thread priority ).

10. In multithreading, what is context-switching )?

Context switching is the process of storing and restoring the CPU status. It enables thread execution to resume execution from the breakpoint. Context switching is a basic feature of multi-task operating systems and multi-threaded environments.

11. How do you ensure that the thread of the main () method is the end thread of the Java program?

We can use the joint () method of the Thread class to ensure that all threads created by the program end before the main () method exits.

12. How do threads communicate?

When resources can be shared among threads, inter-thread communication is an important means to coordinate them. The wait () \ Policy () \ policyall () method in the Object class can be used for inter-thread communication about the lock status of resources.

13. Why are thread communication methods wait (), Policy (), and policyall () defined in the Object class?

Every Java object has a lock (monitor, which can also be a monitor) and wait (), notify () and other methods are used to wait for the lock of the object or notify the monitor of other thread objects to be available. In Java threads, there is no lock or synchronization mechanism available for any objects. This is why these methods are part of the Object class, so that every Java class has a basic method for inter-thread communication.

14. Why must wait (), Policy (), and policyall () be called in the synchronous method or block?

When a thread needs to call the wait () method of an object, the thread must own the lock of the object, then it will release the object lock and enter the waiting state until other threads call the notify () method on this object. Similarly, when a thread needs to call the notify () method of the object, it will release the Lock of this object so that other waiting threads can get the lock of this object. Since all these methods require the thread to hold the object lock, this can only be achieved through synchronization, so they can only be called in the synchronous method or synchronization block.

15. Why are the sleep () and yield () Methods of the Thread class static?

The sleep () and yield () Methods of the Thread class will run on the Thread currently being executed. Therefore, it is meaningless to call these methods on other threads in the waiting state. This is why these methods are static. They can work in the currently being executed thread and prevent programmers from mistakenly believing that they can call these methods in other non-running threads.

16. How to Ensure thread security?

In Java, there are many ways to ensure thread security-synchronization. The atomic class (atomic concurrent classes) is used to implement concurrent locks, the volatile keyword is used, and the unchanged class and thread security class are used. In the thread security tutorial, you can learn more.

17. What is the role of the volatile keyword in Java?

When we use the volatile keyword to modify a variable, the thread will directly read the variable without caching it. This ensures that the variables read by the thread are consistent with those in the memory.

18. Which of the following is a better choice for Synchronous methods and synchronization blocks?

A synchronization block is a better choice because it does not lock the entire object (you can also lock the entire object ). The synchronization method locks the entire object, even if there are multiple unrelated synchronization blocks in this class, which usually causes them to stop executing and wait for the lock on the object to be obtained.

19. How to Create a daemon thread?

You can use the setDaemon (true) method of the Thread class to set the Thread as a daemon. Note that you need to call this method before calling the start () method. Otherwise, an IllegalThreadStateException is thrown.

20. What is ThreadLocal?

ThreadLocal is used to create local variables of a thread. We know that all threads of an object will share its global variables. Therefore, these variables are not thread-safe. We can use the synchronization technology. But when we don't want to use synchronization, we can select the ThreadLocal variable.

Each Thread has its own Thread variables. They can use the get () \ set () method to obtain their default values or change their values within the Thread. ThreadLocal instances usually want them to be associated with the thread state as the private static attribute.

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

ThreadGroup is a class that provides information about a thread group.

The ThreadGroup API is relatively weak and does not provide more functions than the Thread. It has two main functions: Obtain the list of active threads in the thread group and set ncaught exception handler to the thread ). However, the setUncaughtExceptionHandler (UncaughtExceptionHandler eh) method is added to the Thread class in Java 1.5. Therefore, ThreadGroup is outdated and is not recommended for use.

22. What is a Java Thread Dump and how to get it?

Thread dump is a list of JVM active threads. It is useful for analyzing system bottlenecks and deadlocks. There are many ways to get the thread dump-use Profiler, Kill-3 command, jstack tool, and so on. I prefer jstack because it is easy to use and comes with JDK. As it is a terminal-based tool, we can write some scripts to regularly generate thread dump for analysis.

23. What is a Deadlock )? How can we analyze and avoid deadlocks?

A deadlock is a situation where more than two threads are always blocked. In this case, at least two threads and more than two resources are required.

To analyze the deadlock, we need to view the thread dump of the Java application. We need to find out the threads in the status of BLOCKED and the resources they are waiting. Each resource has a unique id. With this id, we can find out which threads already have its object lock.

Avoid nested locks, use locks only as needed, and avoid waiting for an indefinite period is the usual way to avoid deadlocks.

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

Java. util. Timer is a tool class that can be used to schedule a thread to be executed at a specific time in the future. 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. We need to inherit this class to create our own scheduled task and use Timer to schedule its execution.

25. What is a thread pool? How to Create a Java thread pool?

A thread pool manages a group of working threads, and it also includes a queue used to place tasks waiting for execution.

Java concurrent interview questions

1. What is an atomic operation? What atomic classes (atomic classes) are involved in Java Concurrency APIs )?

An atomic operation is an operation task unit that is not affected by other operations. Atomic operations are required to avoid data inconsistency in a multi-threaded environment.

Int ++ is not an atomic operation, so when a thread reads its value and Adds 1, another thread may read the previous value, which leads to an error.

2. What is the Lock interface in Java Concurrency API? What are the advantages of synchronization?

The Lock interface provides more scalable Lock operations than Synchronization Methods and synchronization blocks. They allow a more flexible structure, can have completely different properties, and can support condition objects of multiple related classes.

Its advantages include:

Can make the lock more fair

The thread can respond to the interruption while waiting for the lock.

The thread can try to obtain the lock and return immediately or wait for a period of time when the lock cannot be obtained.

Locks can be acquired and released in different ranges in different order.

3. What is the Executors framework?

Unlimited creation threads can cause application memory overflow. Therefore, creating a thread pool is a better solution, because it can limit the number of threads and recycle them. Using the Executors framework, you can easily create a thread pool.

4. What is a blocking queue? How does one use a blocking queue to implement the producer-consumer model?

The blocking queue does not accept null values. When you try to add null values to the queue, it will throw NullPointerException.

The implementation of blocking queues is thread-safe, all query methods are atomic, and internal locks or other forms of concurrency control are used.

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

5. What are Callable and Future?

Java 5 introduces the java. util. concurrent. Callable interface in the concurrency package. It 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 methods to execute Callable tasks in the thread pool. Because the Callable task is parallel, it must wait for the returned results. Java. util. concurrent. Future object solves this problem. After the Callable task is submitted in the thread pool, a Future object is returned. You can use this object to know the status of the Callable task and obtain the execution result returned by Callable. Future provides the get () method, waiting for the Callable to end and obtaining its execution result.

6. What is FutureTask?

FutureTask is a basic implementation of Future. We can use it with Executors to process asynchronous tasks. Generally, we do not need to use the FutureTask class. When we plan to rewrite some methods of the Future interface and keep the original basic implementation, it becomes very useful. We can only inherit from it and rewrite the methods we need.

7. What is the implementation of concurrent containers?

Java Collection classes all fail quickly, which means that when the set is changed and a thread is traversing the set using the iterator, the next () method of the iterator will throw a ConcurrentModificationException.

Concurrent containers support concurrent traversal and concurrent updates.

The main classes include 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 easily create a thread pool.

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.