Home Java JavaInterview questions Java multi-threading interview questions

Java multi-threading interview questions

Dec 11, 2019 pm 03:05 PM
java

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles