Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the multithreaded interview questions for Java?

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what are the multithreaded interview questions for Java". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the multithreaded interview questions for Java.

121, what is a thread?

Thread is the smallest unit that the operating system can schedule. It is included in the process and is the actual operating unit in the process. Programmers can use it for multiprocessor programming, and you can use multithreading to speed up compute-intensive tasks. For example, if it takes 100 milliseconds for a thread to complete a task, it only takes 10 milliseconds for ten threads to complete the changed task.

122, what's the difference between a thread and a process?

Threads are a subset of processes, and a process can have many threads, each of which performs different tasks in parallel. Different processes use different memory space, while 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?

There are two ways: the instance of the java.lang.Thread class is a thread but it needs to call the java.lang.Runnable interface to execute, because the thread class itself is the calling Runnable interface, so you can inherit the java.lang.Thread class or directly call the Runnable interface to override the run () method to implement the thread.

What is the function and difference between volatile and synchronized?

1,volatile

The variables it modifies do not retain copies and directly access the ones in the main memory.

In the Java memory model, there is main memory, and each thread has its own memory (such as registers). For performance, a thread maintains a copy of the variable to be accessed in its own memory. At some point in the same variable, the value in the memory of one thread may be inconsistent with the value in the memory of another thread, or the value in main memory. A variable declared as volatile means that the variable can be modified by other threads at any time, so it cannot be cache in the thread memory.

2,synchronized

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

First, when two concurrent threads access the synchronized (this) synchronous 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 the code block before it can be executed.

However, when one thread accesses a synchronized (this) synchronization block of object, another thread can still access a non-synchronized (this) synchronization block in that object.

Third, it is especially critical that when one thread accesses a synchronized (this) synchronous code block of object, the access of other threads to all other synchronized (this) synchronous code blocks in object will be blocked.

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

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 the 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 changes their state to Running. Other thread states are Waiting,Blocked and Dead.

126, what is your understanding of thread priority?

Every thread has a priority. Generally speaking, high-priority threads have priority at run time, but this depends on the implementation of thread scheduling, which is OS dependent related to the operating system. We can define the priority of the thread, but this does not guarantee that the high-priority thread will execute in front of the lower-priority thread. The thread priority is an int variable (from 1 to 10), with 1 for the lowest priority and 10 for the highest priority.

127. what is a Deadlock? How to analyze and avoid deadlocks?

A deadlock is a situation in which more than two threads are permanently blocked, which requires at least two or more threads and more than two resources.

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

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

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

If your code is in a process where multiple threads are running at the same time, those threads may run the code at the same time. If the result of each run is the same as that of a single thread, 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 does not make a calculation error when it is used by multiple threads. Obviously you can divide the collection classes into two groups, thread-safe and non-thread-safe. Vector uses synchronous methods to achieve thread safety, while similar ArrayList is not thread safe.

How do I stop a thread in 129Jol Java?

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

130.What is ThreadLocal?

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

Each thread has its own Thread variable, and they can use the get ()\ set () method to get their default values or change their values within the thread. ThreadLocal instances typically want them to be associated with thread state as private static attributes.

What's the difference between 131 Magnum Sleep (), suspend () and wait ()?

Thread.sleep () puts the current thread in a "Not Runnable" state at the specified time. The thread always holds the monitor of the object. For example, a thread is currently in a synchronous block or method, and 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, and a common mistake is to call t.sleep (), where t is a different thread than the current thread. Even if you execute t.sleep (), the current thread goes to sleep, not the t thread. T.suspend () is an outdated method, and the use of suspend () causes the thread to go into a stagnant state, which holds the object's monitor all the time, and suspend () can easily cause deadlock problems.

Object.wait () puts the current thread in an "unrunnable" state, unlike sleep (), where wait is the method of object rather than thread. When calling object.wait (), the thread first acquires the object lock of this object, the current thread must keep synchronized in the lock object, add the current thread to the waiting queue, and then another thread can synchronize the same object lock to call object.notify (), which will wake up the waiting thread and then release the lock. Basically, wait () / notify () is similar to sleep () / interrupt (), except that the former needs to acquire an object lock.

132, what is a thread starving to death and what is a livelock?

When all threads block, or cannot be processed because the required resource is invalid, there are no non-blocking threads to make the resource available. Thread livelocks in JavaAPI can occur in the following situations:

1, when all threads execute Object.wait (0) in the program, the wait method with an argument of 0. The program will livelock 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 do I create a task with a specific interval?

Java.util.Timer is a utility 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 this class to create our own scheduled tasks and use Timer to schedule its execution.

What is the difference between synchronous collections and concurrent collections in 134Jet Java?

Both synchronous and concurrent collections provide appropriate thread-safe collections for multithreading and concurrency, but concurrent collections are more scalable.

Before Java1.5, programmers only had synchronous collections to use and when multithreaded concurrency would lead to contention, 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 the better choice?

Synchronization blocks are a better choice because it does not lock the entire object (of course, you can also let it lock the entire object). Synchronization methods lock the entire object, even if there are multiple unassociated synchronization blocks in the class, which usually causes them to stop execution and wait for the lock on the object to be acquired.

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

It takes expensive resources and time to create a thread, it takes longer to create a thread if the task comes, and the number of threads that a process can create is limited.

To avoid these problems, several threads are created to respond to processing when the program starts. They are called thread pools, and the threads in them are called worker threads.

Starting with JDK1.5, Java API provides an Executor framework that allows you to create different thread pools. For example, a single thread pool handles one task at a time; a fixed number of thread pools or cached thread pools (an extensible thread pool for programs with many short-lived tasks).

What's the difference between invokeAndWait and invokeLater in 137 Java?

These two methods are provided by Swing API to Java developers to update GUI components from the current thread rather than the event dispatch thread. InvokeAndWait () synchronously updates the GUI component, such as a progress bar, and once the progress is updated, the progress bar changes accordingly. If the progress is tracked by multiple threads, the invokeAndWait () method is called to request the event dispatching thread to update the component accordingly. The invokeLater () method is called asynchronously to update the component.

138, what is a busy loop in multithreading?

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

In a multicore system, when a waiting thread wakes up, it may run in another kernel, which rebuilds the cache. It can be used to avoid rebuilding the cache and reduce the time it takes to wait for a rebuild.

Thank you for your reading, the above is the content of "what are the multithreaded interview questions of Java". After the study of this article, I believe you have a deeper understanding of what the multithreaded interview questions of Java have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report