We all know that in Java, there are two means to achieve multi -threaded, one is to continue the Thread class, and the other is to implement the Runable interface.
1. What are the differences between processes and threads?
The process is an execution application, and the thread is an execution sequence within the process. One process can have multiple threads. The thread is also called the lightweight process.
2. How many different ways are there to create threads? Which one do you like? Why?
There are three ways to create a thread:
(1) Inherit the Thread class (2) Implementation of the Runnable interface (3) Applications can use the Executor framework to create a thread pool to achieve the Runnable interface. This is more popular because this does not require the Thread class. In the application design that has inherited other objects, this requires more inheritance (and Java does not support more inheritance) and can only achieve interfaces. At the same time, the thread pool is also very efficient and easy to achieve and use.
3. Summary explanation of several of the use of threads.
During the execution process, threads can be in the following state:
Runnable: The thread is ready to run, and it may not be executed immediately.
Running: The process is executing the code of the thread.
Waiting: thread is in the state of obstruction, waiting for external treatment.
Sleeping: thread is forced to sleep.
I/O block (BLOCKED on I/O): Waiting for I/O operation.
Blocked on Synchronization: Wait for the lock.
Death: The thread is executed.
4. What is the difference between synchronization method and synchronous code block?
In the Java language, each object has a lock. The thread can use the synchronized keyword to obtain the lock on the object. Synchronized keywords can be applied to the method level (coarse granular lock) or code block level (fine particle -size lock).
5. In the monitor (Monitor), how does it do a thread synchronization? What level of synchronization should the program do?
The monitor and lock are used in the Java virtual machine. The monitor monitors a synchronous code block to ensure that there is only one thread to execute synchronous code blocks at a time. Each monitor is associated with a object reference. The thread does not allow the execution synchronization code before obtaining the lock.
6. What is deadlock?
Both processes are waiting for the other party to execute before they can continue to execute. As a result, both processes are in unlimited waiting.
7. How to ensure that n threads can access N resources while not leading to dead locks?
When using multiple threads, a very simple way to avoid dead locks is to specify the order of obtaining locks, and forced threads to obtain locks in the specified order. Therefore, if all threads are locked and released in the same order, there will be no dead locks.