Java thread pool face test

Source: Internet
Author: User
Tags thread class unique id volatile concurrentmodificationexception
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,blicked 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. That's 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.
T1.setuncaughtexceptionhandler (New Uncaughtexceptionhandler () {@Override public void uncaughtexception (Thread t, Throwable e) {System.out.println ("Exception occured:" +e.getmessage ());});  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. Read this document to learn more about generating thread dumps.
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, read this article to learn how to analyze deadlocks.
24. What is a Java Timer class.  How to create a task that has a specific time interval. 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.
Here's an example of a Java timer.
25. What is a thread pool. How to create a Java thread pool. A thread pool manages a set of worker threads, and it also includes a queue for placing tasks waiting to be performed.
Java.util.concurrent.Executors provides an implementation of a Java.util.concurrent.Executor interface to create a thread pool. The thread pool example shows how to create and use a thread pool, or read the Scheduledthreadpoolexecutor example to learn how to create a cycle task.


5. What are 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 callable in the thread pool. Since the callable task is parallel, we have to wait for the result that it returns. The Java.util.concurrent.Future object solved the problem for us. The online pool submits the callable task and returns a future object that we can use to know the status of the callable task and the results of the execution callable return. Future provides a get () method that allows us to wait for the callable to finish and get its execution results.
Read this article for more examples of callable,future.
6. What is Futuretask? Futuretask is a basic implementation of future, and we can use it with executors to handle asynchronous tasks. Usually we do not need to use the Futuretask class, and it becomes very useful when we intend to rewrite some of the methods of the future interface and maintain the original base implementation. We can just inherit from it and rewrite the methods we need. Read the Java Futuretask example and learn how to use it.
7. What is the implementation of the Concurrency container. Java collection classes are fast failures, which means that the next () method of the iterator throws a Concurrentmodificationexception exception when the collection is changed and a thread iterates through the collection using an iterator.
Concurrent containers support concurrent traversal and concurrent updates.
The main classes are Concurrenthashmap, copyonwritearraylist and Copyonwritearrayset, reading this article to learn how to avoid concurrentmodificationexception.
8. What is the Executors class? Executors provides some tools for the executor,executorservice,scheduledexecutorservice,threadfactory and callable classes.
Executors can be used to facilitate the creation of a 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.