Java Engineer interview frequently asked multithreading question "recommended"

Source: Internet
Author: User
Tags extend thread class time in milliseconds

Study questions: 1, talking about the difference between process, thread, and co-processes

Study questions: I hope everyone positive thinking, and can be enthusiastic to say their own ideas, regardless of the right and wrong, as long as it is a kind of improvement, so, hope that the small partners can put their ideas in the message area to give, so that we can learn from each other, the role of inspiration, expand knowledge, improve interview ability ~

2. Do you know the daemon thread? What's the difference between it and non-daemon threads?

When the program finishes running, the JVM waits for the non-daemon thread to close, but the JVM does not wait for the daemon thread. The most typical example of a daemon thread is the GC thread

3. What is multi-threaded context Switch

A multi-threaded context switch is the process by which the CPU control is switched from one thread that is already running to another that is ready and waiting for the CPU to execute.

4. How to create two kinds of threads? What's the difference between them?

By implementing java.lang.Runnable or by extending the Java.lang.Thread class. Implementing the Runnable interface may be better than extending the thread. There are two reasons:

Java does not support multiple inheritance. Therefore, extending the thread class means that the subclass cannot extend other classes. The class that implements the Runnable interface may also extend another class.

Class may only require executable, so the overhead of inheriting the entire thread class is too high.

5. What is the difference between the start () and run () methods in the thread class?

The start () method is used to start the newly created thread, and start () calls the run () method internally, which is not the same as calling the run () method directly. When you call the run () method, only the original thread is called, no new thread is started, and the start () method starts the new thread.

6. How to detect if a thread holds an object monitor

The thread class provides a Holdslock (object obj) method that returns true only if the monitor of the object obj is held by a thread, note that this is a static method, which means that "one thread" refers to the current thread.

7. The difference between runnable and callable

The return value of the run () method in the Runnable interface is void, and what it does is simply to execute the code in the Run () method; the call () method in the callable interface has a return value, is a generic type, and the future, Futuretask mates can be used to get the results of asynchronous execution.

This is actually a very useful feature, because multithreading is more difficult than single-threaded, more complex is an important reason because multithreading is full of unknown, a thread is executed? How long has a thread been executing? Is the data we expect to be assigned when a thread executes? It is impossible to know that all we can do is wait for this multi-threaded task to complete. But Callable+future/futuretask can easily get the results of multi-threaded running, can cancel the task of the thread if the waiting time is too long without getting the data needed

8. What causes thread blocking

Blocking refers to pausing a thread's execution to wait for a condition to occur (such as a resource is ready), and the classmate who learns the operating system must already be familiar with it. Java provides a number of ways to support blocking, let's analyze each of them.

Method description

Sleep () sleep () allows you to specify a period of time in milliseconds as a parameter, which causes the thread to enter a blocking state for a specified amount of time, does not get CPU time, the specified time is over, and the thread re-enters the executable state. Typically, sleep () is used to wait for a resource to be ready: After the test discovery condition is not met, let the thread block for a period of time and then re-test until the condition is met

Suspend () and resume () Two methods are used, suspend () causes the thread to enter a blocking state and does not automatically recover, it must be called by its corresponding resume () in order to enable the thread to re-enter the executable state. Typically, suspend () and resume () are used when waiting for the result of another thread: After the test finds that the result has not yet been generated, the thread is blocked and the other thread produces the result, calling resume () to restore it.

Yield () yield () causes the current thread to discard the currently-divided CPU time, but does not block the current thread, that is, the thread is still in an executable state, and the CPU time may be split again at any time. The effect of calling yield () is equivalent to the scheduler thinking that the thread has executed enough time to go to another thread

Wait () and notify () Two methods are used, wait () causes the thread to enter the blocking state, it has two forms, one allows to specify a period of time in milliseconds as a parameter, and the other without parameters, the former when the corresponding notify () The thread re-enters the executable state when it is called or exceeds the specified time, and the latter must be called by the corresponding notify ().

9, Wait (), notify () and suspend (), the difference between resume ()

At first glance they have nothing to do with the suspend () and the Resume () methods, but in fact they are quite different. The core of the difference is that all of the methods described earlier, blocking will not release the lock (if occupied), and this pair of methods is the opposite. The core differences above lead to a series of differences in detail.

First, all the methods described earlier are subordinate to the Thread class, but the pair is directly subordinate to the object class, which means that all objects have this pair of methods. At first glance this is very magical, but in fact it is very natural, because this pair of methods when blocking to release the lock occupied, and the lock is any object has, call any object's wait () method causes the thread to block, and the lock on the object is freed. The Notify () method that invokes an arbitrary object causes a randomly selected unblocking in the thread that is blocked from calling the wait () method of the object (but is not really executable until the lock is acquired).

Second, all the methods described earlier can be called anywhere, but this pair of methods must be called in the Synchronized method or block, the reason is simple, only in the Synchronized method or block the current line friend occupy the lock, only the lock can be released. Similarly, locks on objects that call this pair of methods must be owned by the current thread, so that locks can be freed. Therefore, this pair of method calls must be placed in such a synchronized method or block where the locked object of the method or block is the object that invokes the pair of methods. If this condition is not met, the program can still compile, but the illegalmonitorstateexception exception will occur at run time.

The above characteristics of the wait () and notify () methods determine that they are often used with the synchronized keyword. Comparing them to the operating system interprocess communication mechanism will find their similarity: the Synchronized method or block provides functionality similar to the operating system primitive, and their execution is not interfered by the multithreading mechanism, which is equivalent to block and wakeup Primitives (this pair of methods are declared as synchronized). Their combination allows us to implement an array of sophisticated inter-process communication algorithms (such as semaphore algorithms) on the operating system, and to solve a variety of complex inter-threading communication problems.

The Wait () and notify () methods are finally explained in two points:

First: Calling the Notify () method causes the unblocked thread to be randomly selected from the thread that was blocked by calling the wait () method of the object, and we cannot predict which thread will be selected, so be careful when programming, and avoid problems with this uncertainty.

Second: In addition to notify (), there is also a method Notifyall () can also play a similar role, the only difference is that the call to the Notifyall () method will be called by the Wait () method of the object is blocked all at once unblocked all the threads. Of course, only the thread that gets the lock can go into the executable state.

When it comes to blocking, it is impossible to talk about deadlocks, and a brief analysis reveals that the suspend () method and the call to the Wait () method, which does not specify a time-out period, can generate a deadlock. Unfortunately, Java does not support deadlock avoidance at the language level, and we must be careful in programming to avoid deadlocks.

We have analyzed the various methods of threading blocking in Java, and we have focused on the wait () and notify () methods, because they are the most powerful and flexible to use, but it also makes them less efficient and prone to error. In practice we should use various methods flexibly in order to achieve our goal better.

11. Conditions for the birth and Death lock

1. Mutex condition: A resource can only be used by one process at a time.

2. Request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.

3. Conditions of deprivation: the resources acquired by the process cannot be forcibly deprived until the end of use.

4. Cyclic wait conditions: a cyclic waiting resource relationship is formed between several processes.

12. Why the Wait () method and the Notify ()/notifyall () method are called in the synchronization block

This is the JDK mandatory, and the Wait () method and the Notify ()/notifyall () method must first obtain the object's lock before calling

What is the difference between the wait () method and the Notify ()/notifyall () method when discarding object monitor

The wait () method and the Notify ()/notifyall () method differ when discarding the object monitor: The Wait () method immediately releases the object monitor, notify ()/notifyall () Method waits for the thread's remaining code to finish before discarding the object monitor.

13. The difference between wait () and sleep ()

The two have been described in detail above, here is a summary:

Sleep () comes from the thread class, and wait () comes from the object class. During the call to the sleep () method, the thread does not release the object lock. Calling the wait method thread frees the object lock

Sleep () does not sell system resources after sleeping, wait for other threads to consume CPU

Sleep (milliseconds) needs to specify a sleeping time when the time is automatically awakened. Wait () needs to be combined with notify () or Notifyall ()

14, why Wait,nofity and Nofityall These methods are not placed in the thread class

One obvious reason is that the locks provided by Java are object-level rather than thread-level, and each object has a lock, which is obtained through the thread. The wait () method in the calling object is meaningful if the thread waits for some locks. If the wait () method is defined in the thread class, it is not obvious which lock the thread is waiting for. Simply put, because Wait,notify and Notifyall are both lock-level operations, they are defined in the object class because the locks belong to the objects.

15. How to wake up a blocked thread

If the thread is blocked by calling the wait (), sleep (), or join () method, it can be disconnected and wake it up by throwing interruptedexception, if the thread encounters io blocking, because IO is implemented by the operating system, Java code has no way of directly contacting the operating system.

Attached QQ group, storage resources and historical information, 1000 capacity (Java Architect Professional Discussion group: 628134587), long by two-dimensional code into the group

Java Engineer interview frequently asked multithreading question "recommended"

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.