Top 50 Java thread interview questions, javatop

Source: Internet
Author: User

[Switch] Top 50 Java thread interview questions, javatop

No matter whether you are a new programmer or veteran, you must have encountered thread problems during the interview. An important feature of Java is its built-in support for concurrency, which makes Java popular among enterprises and programmers. Most well-received Java Development jobs require developers to be proficient in multithreading technology and have rich Java program development, debugging, and optimization experience. Therefore, thread-related issues are often mentioned during interviews.
In a typical Java interview, the interviewer will ask about the basic concepts of the thread, such as: Why do you need to use the thread, how to create the thread, and how to create the thread (for example: inherit the thread class or call the Runnable interface), and then gradually ask the concurrency questions, such as the challenges encountered in the Java concurrent programming process, the Java memory model, JDK introduces higher-level concurrency tools and common design patterns for concurrent programming. Typical multithreading problems include producer consumers, philosophers, readers, and simple bounded buffer. Knowing the basic concept of a thread is far from enough. You must know how to handle deadlocks, race conditions, memory conflicts, thread security, and other concurrency problems. With these skills, you can easily deal with multithreading and concurrent interviews.
Many Java programmers will go to the interview questions before the interview, which is normal. It took a lot of time to collect interview questions and exercises, so I collected 50 hot questions related to Java multithreading and concurrency from many interviewees. I only collected New Interview Questions and did not provide all the answers. You may be wise enough to know these questions for a long time. If you have any questions you don't understand, you can use Google to find the answer. If you cannot find the answer, you can ask me for help in the comments. You can also find some answers here in Java thread Top 12.
The following are top questions related to Java threads. You can use them to prepare for the interview.
1: What is a thread?
A thread is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operating unit of the process. Programmers can program with multiple processors. You can use multiple threads to speed up computing-intensive tasks. For example, if a thread needs 100 milliseconds to complete a task, it takes 10 milliseconds to complete the task with 10 threads. Java provides excellent support for multithreading at the language layer, which is also a good selling point. For more details, click here.
2: What is the difference between a thread and a process?
A thread is a subset of a process. A process can have multiple threads and each thread executes different tasks in parallel. Different processes use different memory spaces, and all threads share the same memory space. Do not mix it with stack memory. Each thread has a separate stack memory to store local data. For more details, click here.
3: How to Implement threads in Java?
There are two ways at the language level. Java. lang. an instance of the Thread class is a Thread, but it needs to call java. lang. run the Runnable interface. Because the Thread class itself is the called Runnable interface, you can inherit java. lang. thread class or directly call the Runnable interface to override the run () method to implement the Thread. For more details, click here.
4: Use Runnable or Thread?
This problem is the follow-up of the above question. We all know that we can implement the Thread by inheriting the Thread class or calling the Runnable interface. The problem is, what is better? When should I use it? This is easy to answer. If you know that Java does not support multiple class inheritance, you can call multiple interfaces. Therefore, if you want to inherit other classes, it is better to call the Runnable interface. For more details, click here.
5: What is the difference between start (: And run (:) in the Thread class?
This question is frequently asked, but it is still possible to distinguish the degree to which the interviewer understands the Java thread model. The start () method is used to start the newly created thread, and the start () method is called internally, which is different from the effect of directly calling the run () method. When you call the run () method, it will only be called in the original thread. If no new thread starts, the start () method will start the new thread. For more information, click here.
6: What is the difference between Runnable and Callable in Java?
Runnable and Callable both represent the tasks to be executed in different threads. Runnable has been available since JDK1.0, and Callable has been added in JDK1.5. The main difference between them is that Callable call (: methods can return values and throw exceptions, while Runnable's run () method does not have these functions. Callable can return the Future object loaded with calculation results. My blog has more details.
7: What is the difference between javasicbarrier and CountDownLatch in Java?
Both CyclicBarrier and CountDownLatch can be used to hold a group of threads waiting for other threads. Unlike CyclicBarrier, CountdownLatch cannot be used again. Click here to view more information and sample code.
8: What is the Java memory model?
The Java Memory Model specifies and guides Java programs to behave deterministic between different memory architectures, CPUs, and operating systems. It is particularly important in the case of multithreading. The changes made to a thread by the Java memory model can be visible to other threads, and the relationship between them is first-in-first-out. This relationship defines some rules to give programmers a clearer idea in concurrent programming. For example, the first link ensures that:
Code in a thread can be executed sequentially, which is called a program order rule.
For the same lock, one unlock operation must occur after the time before another lock operation, also known as a pipe lock rule.
The previous write operation on volatile is called the volatile variable rule before the read operation on the latter volatile.
Any operation in a thread must be called after start () of the thread, also known as the thread startup rule.
All operations of a thread will terminate the rule before the thread ends.
The end operation of an object must be called an object termination rule after the object is constructed.
Portability
I strongly recommend that you read chapter 16th of Java concurrent programming practices to better understand the Java memory model.
9: What is the volatile variable in Java?
Volatile is a special modifier that can only be used by member variables. When a Java concurrent program lacks a synchronization class, the operations of multithreading on member variables are transparent to other threads. The volatile variable ensures that the next read operation will occur after the previous write operation, which is the volatile variable rule of the previous question. Click here to view more volatile-related content.
10: What is thread security? Is Vector a thread security class?
If multiple threads are running simultaneously in the process where your code is located, these threads may run the code at the same time. If the result of each running is the same as that of a single thread, and the value of other variables is the same as expected, it is thread-safe. When the same instance object of a thread-safe counter class is used by multiple threads, no calculation error occurs. Obviously, you can divide collection classes into two groups: thread-safe and non-thread-safe. Vector uses the synchronous method to implement thread security, and its similar ArrayList is NOT thread-safe.
11: What is a race condition in Java?
Competing conditions may cause some bugs in the program concurrency. When multiple threads compete for some resources, a race condition will be generated. If the competition for the first program to be executed fails and is executed later, the whole program will have some uncertain bugs. This kind of bugs is hard to find and will repeat because of random competition between threads. An example is unordered processing. For details, see the answer.
12: how to stop a thread in Java?
Java provides a wide range of APIS, but does not provide APIs for stopping threads. JDK 1.0 has some control methods like stop (), suspend (: and resume (). However, due to the potential deadlock threats, they are discarded in subsequent JDK versions, then, the Java API designer does not provide a compatible and thread-safe method to stop a thread. When run (: Or call (: the thread ends automatically when the method is executed. to manually end a thread, you can use the volatile Boolean variable to exit run () method or cancel the task to interrupt the thread. Click here to view the sample code.
13: What if an exception occurs when a thread is running?
This is a very tricky Java interview I encountered during an interview. Simply put, if exceptions are not caught, the thread will stop running. Thread. UncaughtExceptionHandler is an embedded interface used to handle sudden Thread interruption caused by exceptions not captured. When an uncaptured exception causes Thread interruption, JVM uses the Thread. getUncaughtExceptionHandler () is used to query the thread's UncaughtExceptionHandler and pass the thread and exception as parameters to the handler's uncaughtException () method for processing.
14: how to share data between two threads?
You can use shared objects to achieve this purpose, or use a data structure that is concurrent like blocking a queue. In this tutorial Java inter-thread communication (involving sharing objects between two threads), the producer consumer model is implemented using the wait and consumer y methods.
15: What is the difference between policy and policyall in Java?
This is another issue of the drill-down, because multithreading can wait for a single monitoring lock, Java API designers provide some methods to notify them when the conditions change, but these methods are not fully implemented. The Y () method cannot wake up a specific thread, so it can be used only when a thread is waiting. Policyall () wakes up all threads and allows them to compete for the lock to ensure that at least one thread can continue to run. My blog has more detailed information and sample code.
16: Why are wait, policy, and policyall methods not in the thread class?
This is a design-related issue. It examines the interviewer's views on existing systems and common but seemingly unreasonable things. When answering these questions, you need to explain why it makes sense to put these methods in the Object class, and why not put them in the Thread class. One obvious reason is that the lock provided by JAVA is at the object level rather than the Thread level. Each object has a lock and is obtained through a thread. If the thread needs to wait for some locks, it makes sense to call the wait () method in the object. If the wait () method is defined in the Thread class, it is not obvious which lock the Thread is waiting. Simply put, because wait, policy, and policyall are lock-level operations, they are defined in the Object class because the lock belongs to the Object. You can also read this article to learn more.
17: What is the ThreadLocal variable?
ThreadLocal is a special variable in Java. Each thread has a ThreadLocal, which means that each thread has its own independent variable, and the competition conditions are completely eliminated. It is a good way to get thread security for creating expensive objects. For example, you can use ThreadLocal to make SimpleDateFormat thread-safe, because the class is expensive to create and different instances need to be created for each call, it is not worth using in a local range. If you provide a unique copy of the variable for each thread, this will greatly improve the efficiency. First, reuse reduces the number of expensive objects to be created. Second, you get thread security without using high-cost synchronization or immutability. Another good example of Thread Local variables is the ThreadLocalRandom class, which reduces the number of Random objects that are expensive to create in a multi-threaded environment. View the answer to learn more.
18: What is FutureTask?
In a Java concurrent program, FutureTask indicates an asynchronous operation that can be canceled. It can start and cancel operations, query whether operations are completed, and retrieve operation results. The result can be retrieved only when the operation is completed. If the operation is not completed, the get method will be blocked. A FutureTask object can encapsulate objects that call Callable and Runnable. Because FutureTask also calls the Runnable interface, it can be submitted to Executor for execution.
19: What are the differences between interrupted and isInterruptedd in Java?
The main difference between interrupted (: And isInterrupted () is that the former clears the interrupt status, while the latter does not. The interrupt mechanism of Java multithreading is implemented by using the internal identifier. When Thread. interrupt () is called to interrupt a Thread, the interrupt identifier is set to true. When the interrupt Thread calls the static method Thread. interrupted () to check the interrupt status, the interrupt status is cleared. The non-static method isInterrupted () is used to query the interrupt status of other threads without changing the identifier of the interrupt status. Simply put, any method that throws an InterruptedException exception will clear the interrupt status. In any case, the interruption status of a thread may be changed by the call interruption of other threads.
20: Why do the wait and notify methods need to be called in the synchronization block?
This is mainly because Java APIs require this method. If you do not, your code will throw an IllegalMonitorStateException. Another reason is to avoid competing conditions between wait and policy.
21: why should you check the waiting conditions in the loop?
A thread in the waiting state may receive error alarms and false wakeup. If the thread does not check the waiting condition in the loop, the program will exit without meeting the ending condition. Therefore, when a waiting thread wakes up, it cannot be considered that its original waiting status is still valid. It may change during this period after the notify () method is called and before the waiting thread wakes up. This is the reason why the wait () method works better in the loop. You can create a template in Eclipse to call wait and notify for a try. If you want to know

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.