Several common problems in Java multithreading

  • 2020-04-01 03:51:23
  • OfStack

As we all know, there are two ways to implement multithreading in Java, one is to continue with the Thread class, and the other is to implement the Runable interface.
1. What is the difference between a process and a thread?
A process is an executing application, and a thread is an execution sequence within the process. A process can have multiple threads. Threads are also called lightweight processes.
2. How many different ways can threads be created? Which one do you prefer? Why is that?
There are three ways to create threads:
(1) inherit the Thread class
(2) implement the Runnable interface
(3) applications can use the Executor framework to create a thread pool
Implementing the Runnable interface is more popular because you do not need to inherit the Thread class. In cases where the application design already inherits other objects, this requires multiple inheritance (which Java does not support) and can only implement the interface. Thread pools are also very efficient and easy to implement and use.
3. Briefly explain the available states of threads.
During execution, a thread can be in the following states:
Runnable: a thread is ready to run, and execution may not begin immediately.
Running: the code that the process is executing on the thread.
Waiting: the thread is in a blocked state, Waiting for external processing to finish.
Sleeping: the thread is forced to sleep.
Blocked on I/O: waiting for the I/O operation to complete.
Blocked on Synchronization: wait to acquire the lock.
Dead: the thread completes execution.
4. What is the difference between a synchronized method and a synchronized code block?
In the Java language, each object has a lock. A thread can use the synchronized keyword to acquire a lock on an object. The synchronized keyword can be applied at the method level (coarse-grained locks) or at the code block level (fine-grained locks).
5. How is thread synchronization done inside the Monitor? What level of synchronization should the program do?
Monitors and locks are used together in the Java virtual machine. The monitor monitors a synchronized block of code to ensure that only one thread executes the synchronized block at a time. Each monitor is associated with an object reference. Threads are not allowed to execute synchronized code until they acquire the lock.
What is a deadlock?
A deadlock occurs when both processes are waiting for the other to finish executing before proceeding. The result is that both processes are stuck in an infinite wait.
7. How to ensure that N threads can access N resources without causing deadlocks?
When using multiple threads, a very simple way to avoid deadlocks is to specify the order in which the lock is acquired and force the thread to acquire the lock in the specified order. Therefore, if all threads were to lock and release locks in the same order, deadlocks would not occur.


Related articles: