Home>Article>Java> java multithreading interview questions

java multithreading interview questions

王林
王林 forward
2020-09-17 17:23:50 1637browse

java multithreading interview questions

121, What is a thread?

The thread is the smallest unit that the operating system can perform operation scheduling. It is included in the process and is the actual operating unit in the process. Programmers can use it for multi-processor programming, and you can use multi-threading to speed up computationally intensive tasks. For example, if it takes 100 milliseconds for one thread to complete a task, then it only takes 10 milliseconds to use ten threads to complete the task.

(Recommendations for more related interview questions:java interview questions and answers)

122, what is the difference between threads and processes?

Threads are a subset of processes. A process can have many threads, and each thread performs different tasks in parallel. Different processes use different memory spaces, and all threads share the same memory space. Each thread has a separate stack memory for storing local data.

123, How to implement threads in Java?

Two ways: An instance of the java.lang.Thread class is a thread but it needs to call the java.lang.Runnable interface to execute. Since the thread class itself is the called Runnable interface, you can inherit java.lang .Thread class or directly call the Runnable interface to override the run() method to implement threads.

124, What are the functions and differences between Java keywords volatile and synchronized?

1. Volatile
The variable it modifies does not retain a copy and directly accesses the main memory.
In the Java memory model, there is main memory, and each thread also has its own memory (such as registers). For performance, a thread keeps a copy of the variables it accesses in its own memory. In this way, the value of the same variable in the memory of one thread may be inconsistent with the value in the memory of another thread or the value in main memory at a certain moment. Declaring a variable as volatile means that the variable can be modified by other threads at any time, so it cannot be cached in thread memory.
2. synchronized

When it is used to modify a method or a code block, it can ensure that at most one thread executes the code at the same time.

1. When two concurrent threads access the synchronized (this) synchronization code block in the same object object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing this code block before it can execute this code block.

2. However, when a thread accesses a synchronized (this) synchronized code block of object, another thread can still access the non-synchronized (this) synchronized code block in the object.

3. In particular, when a thread accesss a synchronized (this) synchronization code block in Object, other threads will be blocked by the access of all other synchronized (this) synchronization code blocks in Object.

4. When a thread accesses a synchronized (this) synchronization code block of object, it obtains the object lock of this object. As a result, other threads' access to all synchronized code parts of the object object is temporarily blocked.

5. The above rules are also applicable to other object locks.

125, what are the different thread life cycles?

When we create a new thread in a Java program, its status is New. When we call the thread's start() method, the status is changed to Runnable. The thread scheduler allocates CPU time to threads in the Runnable thread pool and changes their status to Running. Other thread states include Waiting, Blocked and Dead.

126, what is your understanding of thread priority?

Each thread has a priority. Generally speaking, high-priority threads will have priority when running, but this depends on the implementation of thread scheduling, which is related to the operating system. (OS dependent). We can define the priority of threads, but this does not guarantee that high-priority threads will execute before low-priority threads. Thread priority is an int variable (from 1-10), 1 represents the lowest priority, 10 represents the highest priority.

127, what is deadlock? How to analyze and avoid deadlocks?

Deadlock refers to a situation where more than two threads are blocked forever. This situation requires at least two more threads and more than two resources.

To analyze the deadlock, we need to view the thread dump of the Java application. We need to find out which threads are in BLOCKED status and the resources they are waiting for. Each resource has a unique id, using this id we can find out which threads already own its object lock.

Avoiding nested locks, using locks only where needed and avoiding indefinite waiting are common ways to avoid deadlocks.

128, what is thread safety? Is Vector a thread-safe class?

If there are multiple threads running at the same time in the process where your code is located, these threads may run this code at the same time. If the results of each run are the same as those of single-threaded runs, and the values of other variables are the same as expected, it is thread-safe. A thread-safe counter class will not cause calculation errors when the same instance object is used by multiple threads. Obviously you can divide collection classes into two groups, thread-safe and non-thread-safe. Vector uses synchronized methods to achieve thread safety, while ArrayList, which is similar to it, is not thread safe.

(Recommended related video tutorials:java course)

129, How to stop a thread in Java?

Java provides a rich API but does not provide an API for stopping threads. JDK 1.0 originally had some control methods like stop(), suspend() and resume() but they were deprecated in subsequent JDK versions due to potential deadlock threats. After that, the designers of the Java API did not provide a Compatible and thread-safe way to stop a thread. The thread will automatically end when the run() or call() method is executed. If you want to manually end a thread, you can use the volatile Boolean variable to exit the run() method loop or cancel the task to interrupt the thread

130, What is ThreadLocal?

ThreadLocal is used to create local variables of threads. We know that all threads of an object will share its global variables, so these variables are not thread-safe. We can use synchronization technology . But when we don't want to use synchronization, we can choose ThreadLocal variables.

Each thread will have their own Thread variables. They can use the get()\set() method to get their default values or change their values within the thread. ThreadLocal instances typically want their associated thread state to be private static properties.

131, What are the differences between Sleep(), suspend() and wait()?

Thread.sleep() puts the current thread in the "Not Runnable" state at the specified time. The thread always holds the object's monitor. For example, if a thread is currently in a synchronized block or method, other threads cannot enter the block or method. If another thread calls the interrupt() method, it will wake up the "sleeping" thread.

Note: sleep() is a static method. This means that it is only valid for the current thread. A common mistake is to call t.sleep(), (where t is a thread different from the current thread). Even if t.sleep() is executed, the current thread goes to sleep, not the t thread. t.suspend() is an outdated method. Using suspend() will cause the thread to enter a stagnant state. The thread will always hold the monitor of the object. Suspend() can easily cause deadlock problems.

Object.wait() puts the current thread in a "non-runnable" state. The difference from sleep() is that wait is a method of object rather than thread. When calling object.wait(), the thread must first acquire the object lock of this object. The current thread must maintain synchronization on the lock object and add the current thread to the waiting queue. Then another thread can synchronize the same object lock to call object. notify(), which will wake up the original waiting thread and then release the lock. Basically wait()/notify() is similar to sleep()/interrupt(), except that the former needs to acquire the object lock.

132, What is thread starvation and what is livelock?

When all threads are blocked, or the required resources cannot be processed because they are invalid, there are no non-blocking threads to make the resources available. Thread livelock in Java API may occur in the following situations:

1. When all threads execute Object.wait(0) in the program, the wait method with parameter 0 is used. The program will live lock until a thread calls Object.notify() or Object.notifyAll() on the corresponding object.

2. When all threads are stuck in an infinite loop.

133, What is the Java Timer class? How to 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. We need to inherit this class to create our own scheduled tasks and use Timer to schedule its execution.

134, What is the difference between synchronized collections and concurrent collections in Java?

Both synchronized collections and concurrent collections provide suitable thread-safe collections for multi-threading and concurrency, but concurrent collections are more scalable.

Programmers could only use synchronized collections, and it would cause contention when multi-threads were concurrent, hindering the scalability of the system.

Java5 introduces concurrent collections like ConcurrentHashMap, which not only provides thread safety but also improves scalability with modern technologies such as lock separation and internal partitioning.

135, synchronization method or synchronization block, which is a better choice?

Synchronized block is a better choice because it does not lock the entire object (of course you can also let it lock the entire object). Synchronized methods lock the entire object, even if there are multiple unrelated synchronized blocks in the class, which usually causes them to stop executing and need to wait to obtain the lock on the object.

136, What is a thread pool? Why use it?

will become longer when creating a thread, and the number of threads that can be created in a process is limited.

In order to avoid these problems, several threads are created to respond to processing when the program starts. They are called thread pools, and the threads inside are called worker threads.

Starting from JDK1.5, Java API provides the Executor framework so that you can create different thread pools. For example, a single thread pool processes one task at a time; a fixed number of thread pools or a cache thread pool (an extensible thread pool suitable for programs with many short-lived tasks).

137, What is the difference between invokeAndWait and invokeLater in Java?

These two methods are provided by the Swing API to Java developers to update GUI components from the current thread instead of the event dispatch thread. InvokeAndWait() synchronously updates GUI components, such as a progress bar. Once the progress is updated, the progress bar must also change accordingly. If the progress is tracked by multiple threads, then call the invokeAndWait() method to request the event dispatch thread to update the component accordingly. The invokeLater() method calls the update component asynchronously.

138, What is a busy loop in multi-threading?

A busy loop is when the programmer uses a loop to make a thread wait, unlike the traditional methods wait(), sleep() or yield() They all give up CPU control, and the busy loop does not give up the CPU, it just runs an empty loop. The purpose of this is to preserve CPU cache.

In a multi-core system, a waiting thread may be running on another core when it wakes up, which will rebuild the cache. It can be used in order to avoid rebuilding the cache and reduce the time waiting for rebuilding.

Related recommendations:java introductory tutorial

The above is the detailed content of java multithreading interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete