Java multithreading FAQ

Source: Internet
Author: User

Java multithreading FAQ
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 a multi-threaded program, multiple threads are concurrently executedImprove Program EfficiencyThe 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. Other thread statuses include Waiting, Blocked, and Dead.

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.

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.

t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){@Overridepublic void uncaughtException(Thread t, Throwable e) {System.out.println("exception occured:"+e.getMessage());}});
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. Read this document to learn more

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.