Home >Java >JavaInterview questions >Java multi-threading interview questions

Java multi-threading interview questions

(*-*)浩
(*-*)浩Original
2019-12-11 15:05:352956browse

Java multi-threading interview questions

What is a thread?

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. (Recommended study: java interview questions)

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.

What is the difference between thread and process?

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.

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 it java.lang.Thread class or directly call the Runnable interface to override the run() method to implement threads.

What are the functions and differences between the 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 will be modified by other threads at any time, so it cannot be cached in the 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. What is especially critical is that when a thread accesses a synchronized (this) synchronized code block of object, other threads will be blocked from accessing all other synchronized (this) synchronized code blocks in object.

4. When a thread accesses a synchronized (this) synchronized 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.

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.

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. This implementation It is 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.

What is a 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.

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.

The same instance object of a thread-safe counter class will not cause calculation errors when 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.

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. Interrupt thread

What is ThreadLocal?

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

Each thread will have their own Thread variables, and 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.

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.

What is thread starvation and what is livelock?

When all threads are blocked, or cannot be processed because the required resources 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. 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.

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.

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.

Before Java 1.5, programmers could only use synchronized collections, which would cause contention when multi-threads were running concurrently, hindering the scalability of the system.

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

Synchronized methods or synchronized blocks, which one is a better choice?

Synchronized block is a better choice because it does not lock the entire object (of course you can also make 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 acquire the lock on the object.

What is a thread pool? Why use it?

Creating threads costs expensive resources and time. If threads are created only when a task comes, the response time will become longer, and the number of threads that can be created by 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, the 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).

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.

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 method wait(), sleep() or yield() both give up CPU control, but the busy loop does not give up the CPU, it is running 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.

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn