JAVA multithreading and concurrent basic interview questions and Answers __java

Source: Internet
Author: User
Tags sleep thread class volatile





Multithreading and concurrency issues are one of the questions that interviewers prefer to ask in a Java technology interview. Here, the most important questions are listed from the interview point of view, but you should still have a solid grasp of Java multithreading Basics to meet the future problems. (Proofing Note: Very much agree with this view) 

Java Multithreading interview question 1. What is the difference between a process and a thread?



A process is a stand-alone (self contained) operating environment that can be viewed as a program or an application. A thread is a task that is performed in a process. 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 processes, and can share resources in the process. 

2. What are the benefits of multithreaded programming?



In multithreaded programs, multiple threads are executed concurrently to increase the efficiency of the program, and the CPU does not get idle because a thread needs to wait for resources. Multiple threads share heap memory (heap memory), so it is better to create multiple threads to perform some tasks than to create multiple processes. For example, Servlets is better than CGI because Servlets supports multithreading and CGI doesn't 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. A daemon is a thread that executes in the background and does not prevent the JVM from terminating. When no user thread is running, the JVM closes the program and exits. A child 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, then pass it to the thread's constructor, create a thread object, and second, directly inherit the thread class. For more information, read this article about how to create threads in Java. 

5. What are the different thread lifecycles?



When we create a new thread in a Java program, its state is new. When we call the thread's start () method, the state is changed to runnable. The thread scheduler allocates CPU time for threads in the runnable thread pool and says their state changes to running. Other thread states are waiting,blocked and dead. Read this article to learn more about the thread lifecycle. 

6. You can call the thread class's run () method directly.



Sure, but if we call the thread's run () method, it behaves just like a normal method, and you must use the Thread.Start () method to execute our code in a new thread. 

7. How to suspend a running thread for a period of time.



We can use the sleep () method of the thread class to suspend a thread for a period of time. It should be noted that this does not cause the thread to terminate, and once the thread is awakened from hibernation, the thread's state will be changed to runnable, and it will be executed according to the thread schedule. 

8. What is your understanding of the thread priority level?



Each thread is prioritized and, in general, a high-priority thread has precedence at run time, but this relies on the implementation of the thread schedule, which is related to the operating system (OS dependent). We can define the priority of the thread, 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 the 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 state. Once we create a thread and start it, its execution relies on the implementation of the thread scheduler. Time slicing refers to the process of allocating available CPU time to an available runnable thread. The allocation of CPU time can be based on thread priority or time that the thread waits. Thread scheduling is not controlled by the Java Virtual machine, so it is a better choice for the application to control it (that is, don't let your program rely on the priority of the thread). 

10. In multiple threads, what is context switching (context-switching).



Context switching is the process of storing and recovering a CPU state that enables thread execution to resume execution from a breakpoint. Context switching is a basic feature of multitasking operating systems and multithreaded environments. 

11. How do you make sure that the main () method is in the same thread as the end of the Java program.



We can use the joint () method of the thread class to ensure that threads created by all programs end before the main () method exits. Here is an article about the joint () method of the thread class. 

12. How the threads communicate with each other.



When a resource is shared between threads, communication between threads is an important means of reconciling them. The Wait () \notify () \notifyall () method in the object class can be used to communicate the state of a lock on a resource between threads. Click here for more on thread wait, notify and Notifyall. 

13. Why thread-Communication methods Wait (), notify () and Notifyall () are defined in the object class.



Each of the objects in Java has a lock (monitor, also can be monitors) and wait (), notify (), etc. are used for waiting for the lock on the object or for notifying the other thread object that the monitor is available. There is no lock and Synchronizer available for any object in the Java thread. This is why these methods are part of the object class, so that every class in Java has a basic method for communicating between Threads 

14. Why Wait (), notify (), and Notifyall () must be invoked in either the synchronization method or 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 releases the object lock and goes into the waiting state until the other thread calls the Notify () method on the object. Similarly, when a thread needs to invoke the Notify () method of an object, it releases the lock on the object so that other waiting threads can get the object lock. Because all of these methods require that the thread hold the lock of the object so that it can only be implemented through synchronization, they can only be invoked in the synchronization method or in the synchronization block. 

15. Why the sleep () and yield () methods of the thread class are static.



The sleep () and yield () methods of the thread class will run on the currently executing thread. So it makes no sense to increase the use of these methods in other wait-state threads. That's why these methods are static. They can work in the currently executing thread and avoid the programmer's mistaken belief that these methods can be invoked on other non-running threads. 

16. How to ensure thread safety.



There are many ways in Java to ensure thread safety--synchronization, using atomic classes (atomic concurrent classes), implementing concurrent locks, using the volatile keyword, and using invariant classes and thread-safe classes. You can learn more in the thread safety tutorial. 

The volatile keyword is useful 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 in memory. 

18. Sync method and sync block, which is the better choice.



The sync block is a better choice because it doesn't lock the entire object (you can also lock the whole object). The synchronization method locks the entire object, even though there are multiple unrelated synchronization blocks in the class, which usually cause them to stop executing and need to wait for the lock on the object. 

19. How to create a daemon thread.



Using the Setdaemon (true) method of the thread class to set a thread as a daemon, it should be noted that this method is called before the start () method is called, otherwise a Illegalthreadstateexception exception is thrown. 

20. What is Threadlocal?



Threadlocal is used to create a local variable for a thread, we know that all threads of an object share its global variables, so these variables are not thread safe and we can use synchronization techniques. But when we don't want to use synchronization, we can choose the threadlocal variable.



Each thread has its own thread variable, which can use the Get () \set () method to obtain their default values or change their values within a thread. Threadlocal instances are typically expected to be associated with thread state as private static properties. In the threadlocal example this article you can see a small program about threadlocal. 

21. What is thread Group. Why is it recommended to use it?



Threadgroup is a class that is designed to provide information about the thread group.



The Threadgroup API is relatively weak and does not provide more functionality than thread. It has two main functions: one is to get a list of threads that are active in a thread group, and the other is to set up a thread without catching an exception handler (Ncaught exception handler). However, the thread class also adds the Setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) method in Java 1.5, so threadgroup is obsolete and is not recommended for continued use.


1 T1.setuncaughtexceptionhandler (New Uncaughtexceptionhandler () {
2
3 @Override
4 public void Uncaughtexception (Thread t, Throwable e) {
5 SYSTEM.OUT.PRINTLN ("Exception occured:" +e.getmessage ());
6 }
7
8

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.