Java Multi-threading, concurrent basic Interview Knowledge Summary

Source: Internet
Author: User
Tags thread class unique id volatile

(Reproduced from the Concurrent programming network, a slight revision of the collation, more to learn more to share and study together, we would like to become an offer harvester.) )

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. Java multithreaded interview questions 1. What is the difference between processes and threads?

System to do one thing, run a task, this task is a program, each running program is a process, when a program is running, the interior will contain multiple sequential execution flow, each sequence 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 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, so creating multiple threads to perform some tasks is better than creating multiple processes. For example, the servlet is more efficient than CGI because the servlet supports multithreading and is not supported by CGI. 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 a user thread is running. A daemon 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 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. 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 for threads in the runnable thread pool and says their state changes to running (run). Other thread states are waiting (waiting), Blocked (blocking), and dead (death). 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, high-priority threads have precedence at run time, but this relies on the implementation of thread scheduling, which is related to the operating system. 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 runnable (ready) state threads. 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 saving 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 join () method of the thread class to ensure that threads created by all programs end before the main () method exits. 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. 13. Why thread-Communication methods Wait (), notify (), and notifyall () are defined in the object class.

Each of the Java objects has a lock (monitor, also can be monitors) and a wait (), notify () method is used to wait for the lock on the object or to notify other thread objects 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, implementing concurrent locks, using the volatile keyword, and using invariant classes and thread-safe classes. 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. 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 });
22. What is a Java thread dump (thread dump), how to get it.

A thread dump is a list of JVM active threads that are useful for analyzing system bottlenecks and deadlocks. There are many ways to get a thread dump-using the profiler,kill-3 command, the Jstack tool, and so on. I prefer the Jstack tool because it is easy to use and is the JDK's own. Since it is a terminal based tool, we can write some scripts to periodically generate thread dumps for analysis. 23. What is a deadlock (deadlock). How to analyze and avoid deadlocks.

A deadlock is a situation in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.

To analyze deadlocks, we need to look at the thread dumps for the Java application. We need to find those threads with blocked status and the resources they wait for. Each resource has a unique ID, and with this ID we can find out which threads already have its object lock.

Avoiding nested locks, using locks only where needed and avoiding indefinite waiting 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 scheduled with a one-time task or a cycle task.

Java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to inherit this class to create our own timed tasks and use a timer to schedule its execution. 25. What is a thread pool. How to create a Java thread pool. </

Related Article

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.