Java multithreading and java Multithreading
We all know that there are two methods to implement multithreading in java: one is to continue 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 application executed, and a thread is an execution sequence inside the process. A process can have multiple threads. A thread is also called a lightweight process.
2. How can I create a thread? Which one do you like? Why?
There are three ways to create a thread:
(1) inherit the Thread class
(2) Implement the Runnable interface
(3) applications can use the Executor framework to create thread pools.
The Runnable interface is more popular because it does not need to inherit the Thread class. When other objects have been inherited in the application design, this requires multi-inheritance (but Java does not support multi-inheritance) and only interfaces can be implemented. At the same time, the thread pool is also very efficient and easy to implement and use.
3. Briefly explain several available states of the thread.
A thread can be in the following states during execution:
Runnable: The thread is ready to run and cannot be executed immediately.
Running: the code of the thread being executed by the process.
Waiting: The thread is in the blocking status and waits for external processing to end.
Sleeping: The thread is forced to sleep.
Blocked on I/O: wait until the I/O operation is completed.
Blocked on Synchronization: Wait for the lock to be obtained.
Dead: The thread is finished.
4. What is the difference between the synchronization method and the synchronization code block?
In Java, each object has a lock. The thread can use the synchronized keyword to obtain the lock on the object. The synchronized keyword can be applied at the method level (coarse-granularity lock) or code block level (fine-grained lock ).
5. In the Monitor, how does one synchronize threads? What level of synchronization should the program perform?
The monitor and lock are used together in the Java Virtual Machine. The monitor monitors a synchronization code block and ensures that only one thread executes the synchronization code block at a time. Each monitor is associated with an object reference. The thread cannot execute the synchronization code before obtaining the lock.
6. What is a deadlock )?
A deadlock occurs when both processes are waiting for the execution of the other side to continue. The result is that both processes are in infinite waiting state.
7. How can we ensure that N threads can access N resources without causing deadlocks?
When multithreading is used, a very simple way to avoid deadlock is to specify the order in which the lock is obtained and force the thread to obtain the lock in the specified order. Therefore, if all threads lock and release the lock in the same order, no deadlock will occur.