Multithreading (supplement)

Multithreading

1.1 Thread guard

Daemon thread

When each program is running, a daemon thread will be opened by default to monitor our normal program

Simply put, when there is no thread, the JVM needs to exit. At this time, the daemon thread will also exit, mainly to complete garbage collection and other functions.

However, we can use the Thread.setDameon() method to set a thread as a daemon thread

But it must be before starting static, otherwise an error will be reported

1.2 Timer

Timer scheduled tasks, as long as there is a task monitor, it will be a thread
1 to perform the task, 2 to perform the task start time 3 to perform the task interval time

1.3 Deadlock

If you access a locked member method in an object, then all locked member methods in the object are all locked and cannot be accessed by other threads

But it has nothing to do with static, and it has nothing to do with other objects

If you access a locked static method of a class, then all locked static methods in the class are locked and cannot be accessed

But it has nothing to do with members

Different threads occupy the synchronization resources needed by the other party and do not give up, but are waiting for the other party to give up
the synchronization resources they need, forming a thread deadlock.
Solution
Special algorithms and principles
Minimize the definition of synchronization resources
Try to avoid embedding Set synchronization

Deadlock: During the execution process, everyone encounters the other party entering the locking method, causing everyone to be unable to access

Principle:
The execution of a thread needs to be executed sequentially, nested, and locked to execute two objects, and object 1
is executed first. The execution of another thread is completed, and the two objects need to be executed sequentially, nested, and locked, and object 2 is executed first.
In the first thread, when I was going to access object 2, I found it was locked and could only wait.
In the second thread, when I was going to access object 1, it was found to be locked and I could only wait for
each other to be waiting. State, forming a deadlock.

Code block lock
synchronized(xxx)() Code block lock, you can lock the class, you can also lock the object

If the object is locked, when accessing the code block lock, all code block locks and locked member methods in the
object are locked . When accessing the locked member methods in the object, the code block lock will also be locked.

The lock class, when accessing the code block, all code block locks and locked static methods in the
class are locked . When accessing the locked static methods in the class, the code block lock will also be locked

1.4 Thread communication

wait() and notify() and notifyAll()

a) wait(): Make the current thread suspend and give up the CPU, synchronize resources and wait, so that other threads can access and modify shared resources, and the current thread queues up for other threads to call notify() or notifyAll() to wake up and wake up Then wait for the ownership of the monitor to be regained before proceeding.

b) notify(): wake up the thread with the highest priority among the threads waiting for synchronization resources to finish waiting

c) notifyAll (): wake up all threads that are queuing for resources and finish waiting.

Note: These three methods can only be used in the synchronized method or synchronized code block, otherwise
java.lang.IllegalMonitorStateException will be reported
because these three methods must be called by the lock object, and any object can be used as a synchronized lock, so These three methods can only be sounded in the Object class

wait: No parameter or 0 is passed in, indicating that it will not be automatically awakened, and can only be awakened by notifyAll/notify.
You can also pass in a value of type long, in milliseconds, and wake up automatically after a specified time

Note that sleep is a static method in the Thread class, sleeps for a specified time, and will not hand over the lock (other threads still cannot hand over the method)
and wait is a member method in Object, that is, a method that every object has, hangs , Will hand over the lock (other threads can access the method)

1.5 Producers and consumers of interview questions

1.6 Singleton mode

Purpose of singleton mode: Let a class create only one object.
According to the different creation time of the object, there are two kinds of
lazy mode: create the object when it is used for the first time
Hungry man mode: create the object when the class is loaded
Implementation steps: the
construction method is private The
public static method is used to obtain the object. The
private static variable stores the created object

1.7 Thread Pool

Background: Frequently created and destroyed resources that are particularly used, such as threads under concurrent conditions, have a great impact on performance.
Idea: Create multiple threads in advance, put them into the thread pool, get them directly when used, and put them back into the pool after use. It can avoid frequent creation and destruction and realize reuse.

Benefits
a) Improve response speed (reduce the time to create new threads)
b) Reduce resource consumption (reuse threads in the thread pool, no need to create them every time)
c) Facilitate thread management

i. corePoolSize: the size of the core pool
ii. maximumPoolSize: the maximum number of threads
iii. keepAliveTime: how long the thread stays without tasks before it will terminate

The role of the
thread pool : The role of the thread pool is to limit the number of execution threads in the
system. According to the environment of the system, the number of threads can be set automatically or manually to achieve the best results.
Less waste of system resources and more congestion efficiency of the system Not high
Use the thread pool to control the number of threads, and other threads are waiting in line

After a task is executed, take the first task from the queue and start execution

If there is no waiting process in the queue, this resource of the thread pool is in a waiting state

When a new task needs to run, if there are still waiting worker threads in the thread pool at this time, it can start running directly, otherwise it needs to enter the waiting queue

Why use thread pool?
1 Reduce the number of creation and destruction of threads, because each worker thread can be reused to perform multiple tasks

2 The number of threads in the thread pool can be adjusted according to the system's affordability to prevent the server from crashing due to excessive memory consumption (each thread requires about 1MB of memory. The more threads are opened, the more memory is consumed, which eventually leads to crashes. )

1.7.1 How to use

JDK 5.0 has provided thread pool related APIs: ExecutorService and Executors
ExecutorService: the real thread pool interface. Common subclass ThreadPoolExecutor
void execute(Runnable command): execute task/command, no return value, generally used to execute Runnable
Future submit(Callable task): execute task, return value, generally execute Callable
void shutdown(): shutdown Connection pool
Executors: tool class, thread pool factory class, used to create and return different types of thread pools

Executors.newCachedThreadPool(): Create a thread pool that can create new threads as needed

Create a cacheable thread pool. If the length of the thread pool exceeds the processing needs, idle threads
can be recycled flexibly. If there is no one that can be recycled, create a new thread. There is no limit to the size of the thread pool and the number is not fixed.

Executors.newFixedThreadPool(n); Create a reusable thread pool with a fixed number of threads

Create a fixed-length thread pool to control the maximum concurrent
number of threads. Threads that exceed this number will wait in the queue

Executors.newSingleThreadExecutor(): Create a thread pool with only one thread

Create a fixed-length thread pool to support timing and periodic execution of tasks

Executors.newScheduledThreadPool(n): Create a thread pool, which can be scheduled to run commands after a given delay or be executed periodically.

Single-threaded thread pool, only one thread is created. If this thread ends abnormally, then there will be a new thread to replace him.
The thread guarantees the execution order of all tasks and executes them in the order of submission of tasks. Whoever comes first will execute first. .

Guess you like

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