Java multi-threaded face question (i)

Source: Internet
Author: User
Tags unique id

1. The difference between a process and a thread

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

2. What are the benefits of multithreaded programming?

In multithreaded programs, multiple threads are executed concurrently to improve the efficiency of the program, and the CPU does not go 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, Servlets is better than CGI because Servlets supports multithreading and CGI does not 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 thread is a thread that executes in the background and does not prevent the JVM from terminating. When no user thread is running, the JVM shuts down the program and exits. A daemon thread creates a child thread that 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 constructor of thread, create a thread object, and inherit the thread class directly.

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 to threads in the runnable thread pool and says their state changes to running. Other thread states also have waiting,blocked and dead.

6. Can I call the run () method of the thread class directly?

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

7. How do I get a running thread to pause for a while?

We can use the sleep () method of the thread class to suspend a thread for a while. It is important to note that this does not cause the thread to terminate, and once the thread is awakened from hibernation, the state of the thread will be changed to runnable, and it will be executed according to the thread dispatch.

8. What is your understanding of thread priorities?

Each thread has a priority, in general, a high-priority thread will have priority at run time, but this depends on the implementation of the thread schedule, which is operating system-related (OS dependent). We can define the priority of threads, 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 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 depends on the implementation of the thread scheduler. Time sharding refers to the process of allocating available CPU time to available runnable threads. The allocated CPU time can be based on the thread priority or the time the thread waits. Thread scheduling is not controlled by the Java Virtual machine, so it is better to control it by the application (i.e. don't let your program depend on the priority of the thread).

10. What is context switching (context-switching) in multi-threading?

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

11. How do you make sure that the thread on which the main () method resides is the last thread that the Java program ends?

We can use the join () method of the thread class to ensure that all program-created threads end before the main () method exits.

12. How are the threads communicating?

When resources are shared between threads, inter-thread communication is an important means of reconciling them. The Wait (), notify (), Notifyall () methods in the object class can be used to communicate between threads about the state of a lock on a resource.

13. Why is the thread communication method Wait (), notify (), and notifyall () defined in the object class?

Every object in Java has a lock (monitor, can also be a monitor) and wait (), notify (), and so on to wait for the object's lock or to notify other thread objects that the monitor is available. There are no locks and synchronizers available for any object in Java threads. That's why these methods are part of the object class, so that every class in Java has a basic method for inter-thread communication

14. Why wait (), notify (), and Notifyall () must be called in the synchronization method or in 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 will release the object lock and enter the wait state until the other thread calls the Notify () method on the object. Similarly, when a thread needs to invoke the object's notify () method, it releases the lock on the object so that other waiting threads can get the object lock. Since all of these methods require a thread to hold the lock on the object, this can only be done by synchronization, so they can only be called in a synchronous method or in a synchronous block.

15. Why is the sleep () and yield () method of the thread class static?

The sleep () and yield () methods of the thread class will run on the currently executing thread. So it makes no sense to raise these methods on other waiting threads. That's why these methods are static. They can work in the currently executing thread and prevent programmers from mistakenly thinking that these methods can be called on other non-running threads.

16. How to ensure thread safety?

There are many ways to ensure thread safety in Java-synchronization, using atomic classes (atomic concurrent classes), implementing concurrent locks, using the volatile keyword, and using immutable classes and thread-safe classes.

How does the volatile keyword work 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 with the memory.

18. What is the better choice for synchronous and synchronous blocks?

Synchronizing a block is a better choice because it does not lock the entire object (you can, of course, lock the entire object). The synchronization method locks the entire object, even if there are multiple unrelated synchronization blocks in the class, which usually causes them to stop executing and to wait for a lock on the object.

19. How do I create a daemon thread?

Using the Setdaemon (true) method of the thread class to set the thread as the daemon thread, it is important to note that this method needs to be called before the start () method is called, or the illegalthreadstateexception exception will be thrown.

20. What is Threadlocal?

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

Each thread will have their own thread variable, which can use the Get () \set () method to get their default values or change their values inside the thread. Threadlocal instances are typically the private static property that you want them to associate with the thread state.

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

Threadgroup is a class whose purpose is to provide information about thread groups.

The Threadgroup API is weak, and it does not provide more functionality than thread. It has two main functions: one is to get the list of active threads in the thread group, and the other is to set the uncaught exception handler (Ncaught exception handler) to the thread setting. However, in Java 1.5 The thread class has also added the Setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) method, so Threadgroup is obsolete and is not recommended for further use.

22. What is a Java thread dump (thread dump) and how do I get it?

A thread dump is a list of JVM active threads, which is useful for parsing system bottlenecks and deadlocks. There are many ways to get a thread dump--using the profiler,kill-3 command, Jstack tools, and so on. I prefer the Jstack tool because it is easy to use and comes with a JDK. Since it is a terminal-based tool, we can write some scripts to generate thread dumps periodically for analysis. Read this document to learn more about generating thread dumps.

23. What is a deadlock (Deadlock)? How do I analyze and avoid deadlocks?

Deadlocks are situations in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.

Parsing deadlocks, we need to look at thread dumps for Java applications. We need to identify the threads that are blocked and the resources they wait for. Each resource has a unique ID, which we can use to find out which threads already have their object locks.

Avoiding nested locks, using locks only where needed and avoiding waiting indefinitely is the usual way to avoid deadlocks.

24. What is the Java Timer class? How do I create a task with 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 used to schedule one-time tasks or periodic tasks.

Java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to inherit the class to create our own timed task and use the timer to schedule its execution.

25. What is a thread pool? How do I create a Java thread pool?

A thread pool manages a set of worker threads, and it also includes a queue that is used to place tasks that are waiting to be executed.

Java.util.concurrent.Executors provides an implementation of the Java.util.concurrent.Executor interface for creating a thread pool.

Java multi-threaded face question (i)

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.