Multithreading, synchronization mechanism, lock

Multithreading

1. Multithreading

1.1 Basic concepts: program, process, thread

A program is a set of instructions written in a certain language to complete a specific task. A
piece of static code, a static object.

A process is an execution process of a program, or a running program,
a dynamic process: a process of its own generation, existence, and demise. --life cycle

Thread, a process can be further refined into a thread, which is an execution path within a program.
Thread as the unit of scheduling and execution, each thread has an independent running stack and program counter (pc)

1.2 Understanding of single-core CPU and multi-core CPU

a) Single-core CPU is actually a kind of fake multi-thread, because in a time unit, only one thread can be executed.
b) A Java application java.exe actually has at least three threads: main() main thread, gc() garbage collection thread, exception handling thread. Of course, if an exception occurs, it will affect the main thread.

1.3 Parallel and Concurrency

Single thread is actually more efficient than multithreading, because multithreading requires thread switching, which consumes more resources, but the response time of multithreading to users is faster

Concurrency: In terms of a single core, a CPU receives many requests, and these requests can only be executed one by one. At this time, the situation of multiple requests is called concurrency; of course, multiple cores can also be concurrent;
parallel: for multiple cores In other words, two or more CPUs receive many requests at the same time, and each CPU can execute one request, and this execution is performed at the same time. Two or more CPUs execute the request at the same time, which is called This is parallel; of course, if there are enough requests, each CPU has a request for execution, and the rest of the requests have to be queued for execution. At this time, the situation of waiting for execution is called multi-threaded concurrency. Of course, these requests are all the same. Time issued.

1.4 Advantages of using multithreading

Improve the responsiveness of the application. It is more meaningful to the graphical interface and can enhance the user experience.
Improve the CPU utilization of the computer system and
improve the program structure. Divide a long and complex process into multiple threads and run independently, which is conducive to understanding and
modification

1.5 When do you need multithreading

The program needs to perform two or more tasks at the same time; when the
program needs to implement some waiting tasks, such as user input, file read and write operations, network operations, search, etc.;
when some background running programs are required;

1.6 Creation method

There are two ways to create a thread, but there is only one way to start a thread, which is to call the start() method in the thread object

1.6.1 Inheritance

The first: inherit the Thread class and override the run() method

The Java language JVM allows the program to run multiple threads, which
is reflected by the java.lang.Thread class.

The characteristics of the Thread class
Each thread completes the operation through the run() method of a specific Thread object. The main body of the run() method is often called the thread body.
The thread is started by the start() method of the Thread object. Instead of calling run() directly

Constructor
Thread(): create a new Thread object
Thread(String threadname): create a thread and specify the thread instance name
Thread(Runnable target): specify the target object for creating a thread, it implements the
run method in the Runnable interface
Thread(Runnable target, String name): Create a new Thread object

Creation process
Inherit the Thread class
1) Define subclasses to inherit the Thread class.
2) Override the run method in the Thread class in the subclass.
3) Create a Thread subclass object, that is, create a thread object.
4) Call the start method of the thread object: start the thread and call the run method.

1.6.2Runnable

The second way to create a thread: implement the Runable interface and override the run() method to
start or use the start() method in the thread object

1.7 The difference between inheritance and implementation

Inherit Thread: Thread code is stored in the run method of the Thread subclass.
Implement Runnable: Thread code exists in the run method of the subclass of the interface.

The benefits of the implementation method
avoid the limitations of single inheritance.
Multiple threads can share objects of the same interface implementation class, which is very suitable for multiple same threads to process the same resource.

1.8 Common methods

start(): the only way to start a thread
setName(): set the name of the thread, the default is Thread-0, Thread-1... and so on
getName(): get the name of the thread
setPriority(): set the thread priority
getPriority(): Get thread priority
static currentThread(): Get the memory address of the current thread (get the current thread object)
static sleep(): Put the current thread to sleep, the parameter is the number of milliseconds

1.9 Time slice allocation

Java's scheduling method
composes a first-in, first-out queue with priority threads (first come, first served), using time slice strategy
For high priority, using a preemptive strategy of priority scheduling

1.10. Priority use

Priority: There are 10 levels in java, 1-10

There are also three constants provided in the Thread class, which hold 1, 5, and 10 respectively. The
highest priority : 10 Thread.MAX_PRIORITY is
normal: 5 Thread.NORM_PRIORITY is the
lowest: 1 Thread.MIN_PRIORITY

getPriority(): Get the thread priority
setPriority(): Set the thread priority

When the thread is created, it inherits the priority of the parent thread. The priority of Thread is 5. The
low priority is just a low probability of scheduling, and it is not necessarily called after the high-priority thread.

1.11 Life Cycle

Overview

Create --> Ready --> Run --> Block --> Resurrection --> Block... --> Death

Several states of threads are defined in the JDK with the Thread.State class

New: When an object of the Thread class or its subclasses is declared and created, the new thread object is in a new state

Ready: After the thread in the newly created state is started(), it will enter the thread queue to wait for the CPU time slice. At this time, it has the conditions to run, but no CPU resources are allocated

Run: When the ready thread is scheduled and obtains CPU resources, it enters the running state. The run() method defines the operation and function of the thread

Blocking: In a special case, when the user is artificially suspended or performing input and output operations, give up the CPU and temporarily suspend its execution, enter the blocking state and
die: the thread has completed all its work or the thread is forcibly terminated in advance Or an abnormality leads to the end

static currentThread(): Static method, used to get the object of the current thread,
write in which thread, get the object of which thread

static sleep(long m): static method, let the current thread sleep,
need to pass in the corresponding number of milliseconds, write which thread to sleep which thread

1.12 Thread control

Interrupt(): Forcibly wake up a thread will report an error~

sleep() let the current thread sleep

There are two ways to wake up sleeping threads
: 1. Normal wakeup: when the sleep time is up.
2. Abnormal wakeup: force interruption of sleep and report an exception

1.13 Join

Join: Thread merge, let the specified thread execute after the thread has finished running

1.14 Yield

Thread.yeild: Suspend the currently executing thread and execute other threads
1 Static method, which means which thread is written in, which thread
gives way to the thread of the same priority, and different priorities do not give way to
the current 3 When the thread is executed (get the time slice), give the execution opportunity (time slice) to other threads

1.15 stop

stop: Terminate a thread, which is prone to problems and not very safe. It is not recommended.
You can use the form of identifier to end

1.16 Thread synchronization mechanism

When multiple threads operate on the same data, in order to ensure the consistency
of the data, the essence of thread synchronization is data synchronization, which is a safety mechanism.

Asynchronous programming: The threads are completely independent, and whoever runs will not be affected by other threads

Synchronous programming: Threads are not independent and affect each other. A function must be executed by only one thread at the same time, mainly for data security

Reasons for synchronization:
data synchronization, for data security, in some cases, synchronization can be understood as temporarily converting multi-threaded to single-threaded

As long as the synchronized member method is added to the method, it means that the method cannot be accessed by multiple threads at the same time

The lock is owned by every object. Synchronized is only a continuous action to lock the lock, and multiple threads must save the same object in order to use the same lock, to exclude each other, and to ensure data security

If multiple threads are not saving the same object, even though they are different objects of the same class, there is no way to exclude each other

Solution
Provides a professional solution to the security problem of multithreading: synchronization mechanism
1. Synchronization code block:
synchronized (object) { // code that needs to be synchronized; }

2. Synchronized can also be placed in the method declaration, indicating that the entire method is a synchronized method.
For example:
public synchronized void show (String name){ …. }

1.17 Lock

Starting from JDK 5.0, Java provides a more powerful thread synchronization mechanism—synchronization is achieved by explicitly defining synchronization
lock objects. Synchronization locks use Lock objects to act as.

The java.util.concurrent.locks.Lock interface is a tool for controlling multiple threads to access shared resources. The lock provides exclusive access to shared resources. Only one thread can lock the Lock object at a time. The Lock object should be acquired before the thread starts to access the shared resource.

The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized. In the realization of thread-safe control, ReentrantLock is more commonly used, which can explicitly lock and release locks.

1.17 Comparison of synchronized and Lock

1. Lock is an explicit lock (manually open and close the lock, don’t forget to close the lock), synchronized is an implicit lock, automatically released out of the scope
2. Lock only has code block locks, synchronized has code block locks and method locks
3. Using Lock locks, JVM will spend less time to schedule threads, better performance. And has
better scalability (provide more sub-categories)

Priority order:
Lock synchronization code block (has entered the method body and allocated corresponding resources) synchronization method
(outside the method body)

Guess you like

Origin blog.csdn.net/MIRACLE_Ying/article/details/113362504