These multithreaded questions, some from the site, some from their own thinking. There may be some problem online, there may be some questions the corresponding answers and, also may be a little fellow netizens also are seen, but the focus of this writing is that all problems will be according to own understanding to answer again, don’t go to the online answer, so there may be some problems about wrong, can correct hope you feel free to comment.

More Java study notes, interview questionsClick here to】 get

Java multi-threaded interview questions

1. What’s the difference between a process and a thread?

A process is a self-contained runtime environment that can be thought of as a program or an application. A thread is a task that is executed in a process. The Java runtime environment is a single process that contains different classes and programs. Threads can be called lightweight processes. Threads require fewer resources to create and reside in a process, and can share resources in a process.

2. What are the benefits of multithreaded programming?

In multithreaded programs, multiple threads are executed concurrently to improve program efficiency, so that the CPU does not become idle because one thread is waiting for resources. Multiple threads share heap memory, so it is better to create multiple threads to perform some tasks than multiple processes. For example, Servlets are better than CGI because Servlets support multithreading whereas CGI does not.

3. What’s the difference between user threads and daemon threads?

When we create a thread in a Java program, it is called a user thread. A daemon thread is one that executes in the background and does not prevent the JVM from terminating. When no user threads are running, the JVM closes the program and exits. A child created by a daemon thread is still a daemon thread.

4. How do we create a thread?

There are two ways to create a Thread. One is to implement the Runnable interface and pass it to the Thread constructor to create a Thread object. The other is to inherit Thread directly.

5. What are the different thread lifecycles?

When we create a New thread in a 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 the threads in the Runnable thread pool and changes their state to Running. Other thread states include Waiting, Blocked, and Dead.

6. Can I call the run() method of Thread directly?

Sure, but if we call the Thread’s run() method, it will behave like a normal method. In order to execute our code in a new Thread, we must use thread.start ().

7. How do I suspend a running thread for a period of time?

We can pause the Thread for a period of time using the Sleep() method of the Thread class. Note that this does not terminate the thread; once it is awakened from sleep, the thread’s state is changed to Runnable and, according to the thread’s schedule, it is executed.

8. What is your understanding of thread priorities?

Each thread has a priority. In general, higher-priority threads have priority at runtime, but this depends on the implementation of thread scheduling, which is OS dependent. We can define the priority of threads, but this does not guarantee that the higher-priority threads will execute before the lower-priority threads. Thread priority is an int variable (1-10), with 1 representing the lowest priority and 10 representing the highest.

9. What are Thread Schedulers and Time Slicing?

The thread scheduler is an operating system service that allocates CPU time to threads in the Runnable state. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. Time sharding is the process of allocating available CPU time to available Runnable threads. CPU time can be allocated based on thread priority or how long a thread waits. Thread scheduling is not controlled by the Java Virtual Machine, so it is better for your application to control it (i.e., don’t make your program dependent on thread priorities).

10. What is context-switching in multithreading?

Context switching is the process of storing and restoring the STATE of the CPU, which enables threaded execution to resume execution from a breakpoint. Context switching is an essential feature of multitasking operating systems and multi-threaded environments.

11. How do you ensure that the main() method is in the thread on which the Java program ends?

We can use the joint() method of the Thread class to ensure that all program-created threads end before the main() method exits.

12. How do threads communicate?

When threads can share resources, inter-thread communication is an important means to coordinate them. The methods wait()\notify()\notifyAll() in the Object class can be used to communicate between threads about the state of a lock on a resource.

13. Why are the thread communication methods wait(), notify(), and notifyAll() defined in class Object?

Each object in Java has a lock (monitor, which can also be a monitor) and methods such as wait(), notify() are used to wait for an object’s lock or to notify other threads that the object’s monitor is available. There are no locks or synchronizers available to any object in a Java thread. That’s why these methods are part of the Object class, so that every Java class has a basic method for interthread communication, right

14. Why must wait(), notify(), and notifyAll() be called in a synchronized method or synchronized block?

When a thread calls the wait() method on an object, the thread must own the lock on the object. It then releases the lock and enters the wait state until another thread calls the notify() method on the object. Similarly, when a thread needs to call the notify() method on an object, it releases the lock on the object so that other waiting threads can get the lock. Since all of these methods require the thread to hold the lock on the object and thus can only be implemented through synchronization, they can only be called in a synchronized method or synchronized block.

15. Why are the sleep() and yield() methods of Thread static?

The sleep() and yield() methods of the Thread class run on the Thread currently executing. So it makes no sense to call these methods on other threads that are in the wait state. That’s why these methods are static. They can work in the thread that is currently executing, and avoid the programmer’s mistake of thinking that they can be called in other, non-running threads.

16. How do I ensure thread safety?

There are many ways to ensure thread-safety in Java — synchronization, using atomic concurrent classes, implementing concurrent locking, using volatile keywords, using immutable and thread-safe classes.

17. What does the volatile keyword do in Java?

When we use the volatile keyword to modify a variable, the thread reads the variable directly and does not cache it. This ensures that the variables read by the thread are consistent with those in memory.

18. Which is the better choice, the synchronized method or the synchronized block?

A synchronized block is a better choice because it doesn’t lock the whole object (you can also have it lock the whole object). Synchronous methods lock the entire object, even if there are multiple unrelated synchronized blocks in the class, which usually causes them to stop executing and wait for the lock to be acquired on the object.

How do I create a daemon thread?

Using Thread class setDaemon (true) method, a Thread can be set to daemon Thread, it is important to note that need to be in front of the call start () method calls this method, otherwise will be thrown IllegalThreadStateException anomalies.

20. What is ThreadLocal?

ThreadLocal is used to create local variables for a thread. We know that all threads of an object share its global variables, so these variables are not thread-safe. We can use synchronization techniques. But when we don’t want to use synchronization, we can select the ThreadLocal variable.

Each Thread has its own Thread variable, which can use the get()\set() method to get its default value or change its value within the Thread. ThreadLocal instances are usually expected to have private static properties associated with the thread state.

21. What is Thread Group? Why is it not recommended?

ThreadGroup is a class whose purpose is to provide information about a ThreadGroup.

The ThreadGroup API is weak and provides no more functionality than Thread. It has two main functions: one is to get a list of active threads in a thread group; The second is to set the thread to set the ncaught exception handler. But the Thread in the Java 1.5 class also added setUncaughtExceptionHandler (UncaughtExceptionHandler eh) method, so the ThreadGroup is outdated, continue to use is not recommended.

22. What is Java Thread Dump and how do I get it?

A thread dump is a list of active THREADS in the JVM, which is useful for analyzing system bottlenecks and deadlocks. There are many ways to get a thread dump — using profilers, the Kill -3 command, the jStack tool, and so on. I prefer the JStack tool because it’s easy to use and comes with the JDK. Since it is a terminal based tool, we can write scripts that periodically generate thread dumps for analysis.

23. What is a Deadlock? How to analyze and avoid deadlocks?

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

To analyze deadlocks, we need to look at the thread dump of the Java application. We need to identify the threads whose state is BLOCKED and the resources they are waiting for. Each resource has a unique ID that we can use to find out which threads already own its object lock.

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

What is the Java Timer class? How do I create a task with a specific time 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 either one-time 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 task and schedule its execution using the Timer.

What is a thread pool? How do I create a Java thread pool?

A thread pool manages a set of worker threads, and it also includes a queue to hold tasks waiting to be executed.

Java. Util. Concurrent. Executors provides a Java. Util. Concurrent. The realization of the Executor interface is used to create a thread pool.

26. Four thread pools

The top-level interface for a thread pool in Java is an Executor, but an Executor is not technically a thread pool

It’s just a tool for executing threads. The real thread pool interface is ExecutorService.

27. Thread Lifecycle (state)

When a thread is created and started, it does not enter the execution state as soon as it is started, nor does it remain in the execution state. During the life of a thread, it passes through five states: New, Runnable, Running, Blocked, and Dead. In particular, when a thread is started, it cannot “hog” the CPU all the time, so the CPU needs to switch between multiple threads, and the thread state will switch between running and blocking many times

More Java study notes, interview questionsClick here to】 get

Java concurrent interview questions

1. What is an atomic operation? What are the atomic classes in the Java Concurrency API?

An atomic operation is an operation task unit that is unaffected by other operations. Atomic operations are necessary to avoid data inconsistency in a multithreaded environment.

Int++ is not an atomic operation, so when one thread reads its value and incrementing it by 1, the other thread might read the previous value, which would raise an error.

To solve this problem, it is necessary to ensure that the increment operation is atomic, and before JDK1.5 we could use synchronization techniques to do this. To JDK1.5, Java. Util. Concurrent. Atomic package provides an int and long types of classes, they can be automatically guarantee for their operation is atomic and don’t need to use the synchronization.

What is the Lock Interface in the Java Concurrency API? What are the advantages over synchronization?

The Lock interface provides more scalable locking operations than synchronized methods and synchronized blocks. They allow for more flexible structures, can have completely different properties, and can support conditional objects for multiple related classes.

Its advantages are:

  • Can make the lock more fair
  • You can interrupt a thread’s response while waiting for a lock
  • You can have a thread try to acquire a lock and either return immediately or wait for a period of time when the lock cannot be acquired
  • Locks can be acquired and released in different ranges and in different orders

3. What is Executors framework?

Executor framework with Java. Util. Concurrent. The Executor interface was introduced in Java 5. The Executor framework is a framework for invoking, scheduling, executing, and controlling asynchronous tasks according to a set of execution policies.

Unlimited creation threads can cause an application memory overflow. Creating a thread pool is a better solution because you can limit the number of threads and recycle them. Use the Executors framework to easily create a thread pool.

4. What is a blocking queue? How to implement the producer-consumer model using blocking queues?

Java. Util. Concurrent. BlockingQueue feature is: when the queue is empty, the operation of the access to or remove elements from the queue will be blocked, or when the queue is full, add elements in the queue will be blocked.

Blocking queues do not accept null values and will throw a NullPointerException when you try to add a null value to the queue.

The blocking queue implementation is thread-safe, and all query methods are atomic and use internal locks or other forms of concurrency control.

The BlockingQueue interface is part of the Java Collections framework and is primarily used to implement producer-consumer issues.

5. What are Callable and Future?

Java 5 in concurrency package introduced in Java. Util. Concurrent. Callable interface, it is similar to the Runnable interface, but it can return an object or throw an exception.

The Callable interface uses generics to define its return type. The Executors class provides some useful methods for executing Callable tasks in the thread pool. Since the Callable task is parallel, we must wait for the result it returns. Java. Util. Concurrent. The Future object to solve the problem for us. A Future object is returned after a thread pool submits a Callable task. It is used to know the status of the Callable task and to obtain the execution result that the Callable returns. The Future provides a get() method that lets us wait for the Callable to finish and get its execution result.

6. What is FutureTask?

FutureTask is a foundation implementation of Future that we can use along with Executors to handle asynchronous tasks. In general we don’t need to use the FutureTask class, but it’s useful just when we’re going to override some of the methods of the Future interface and keep the original basic implementation. We can just inherit from it and rewrite the methods we need.

7. What is the implementation of a concurrent container?

Java collection classes are rapid failure, this means that when the set is changed and a thread when using iterators iterate through the set, iterator next () method will throw ConcurrentModificationException.

The concurrent container supports concurrent traversal and concurrent updates. The main classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet.

8. What is the Executors class?

Executors provide methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.

Executors can be used to easily create a thread pool

Good today’s interview questions to share here, if you think the article is helpful to you, remember one key three even a click oh ~ more Java study notes, interview questions can be [click here] to obtain