当前位置:网站首页>Notes (IV) - multithreading

Notes (IV) - multithreading

2022-06-10 22:17:00 Li_ XiaoJin

Record your knowledge about multithreading .

1. Java After thread creation , call start() Methods and run() The difference between

1) start Method : use start Method to start a thread , The real implementation of multithreading , There is no need to wait run The method body code is executed and continues to execute the following code directly . By calling Thread Class start() Method to start a thread , This thread is now ready ( Can run ) state , Not running , Once you get it cpu Time slice , We'll start run() Method , Here's how run() Called thread body , It contains the contents of the thread to be executed ,Run End of method run , This thread will terminate . 2) run(): run() Method is just a common method of class , If called directly run Method , The main thread is still the only thread in the program , There is only one program execution path , Or in sequence , Or wait ,run After the method body is executed, you can continue to execute the following code , This does not achieve the purpose of writing threads .

summary : call start Method to start the thread , and run It's just thread A normal method call of , Or in the main thread . Both methods should be familiar , Put the code that needs parallel processing in run() In the method ,start() Method start thread will automatically call run() Method , This is from jvm The memory mechanism of . also run() The method must be public Access right , The return value type is void.

2. Common thread pool mode and different thread pool usage scenarios

Five thread pools , Four rejection strategies , Three kinds of blocking queues Three kinds of blocking queues : BlockingQueue workQueue = null;

workQueue = new ArrayBlockingQueue<>(5);// Array based fifo queue , bounded 

workQueue = new LinkedBlockingQueue<>();// Fifo queue based on linked list , unbounded 

workQueue = new SynchronousQueue<>();// Unbuffered waiting queue , unbounded 

Four rejection strategies : RejectedExecutionHandler rejected = null;

rejected = new ThreadPoolExecutor.AbortPolicy();// Default , When the queue is full and the task is lost, an exception is thrown 

rejected = new ThreadPoolExecutor.DiscardPolicy();// When the queue is full, it is not abnormal to lose a task 

rejected = new ThreadPoolExecutor.DiscardOldestPolicy();// Delete the task that entered the queue first , Then try to join the queue 

rejected = new ThreadPoolExecutor.CallerRunsPolicy();// If adding to the thread pool fails , Then the main thread will execute the task itself 

Five thread pools : ExecutorService threadPool = null;

threadPool = Executors.newCachedThreadPool();// Buffered thread pool , Number of threads  JVM  control 

threadPool = Executors.newFixedThreadPool(3);// Fixed size thread pool 

threadPool = Executors.newScheduledThreadPool(2);

threadPool = Executors.newSingleThreadExecutor();// Single threaded thread pool , Only one thread is working 

threadPool = new ThreadPoolExecutor();// Default thread pool , There are many controllable parameters 

Refer to my previous article :https://lixj.fun/archives/2020-04-30-11-39-14

CachedThreadPool The characteristic of this kind of thread pool is that there are no core threads in it , All non core threads , Its maximumPoolSize Set to Integer.MAX_VALUE, Threads can be created indefinitely , When all threads in the thread pool are active , The thread pool creates new threads to handle new tasks , Otherwise, idle threads will be used to process new tasks , Idle threads of this kind of thread pool have a timeout mechanism ,keepAliveTime It works here , The length of 60 second , exceed 60 Seconds of idle threads will be recycled , When all thread pools are idle , Threads in the thread pool will be recycled due to timeout , So it hardly takes up any system resources . The task queue uses SynchronousQueue, This queue can't insert tasks , Carry out the task as soon as possible , therefore CachedThreadPool Compare It is suitable for tasks with large amount of tasks but less time .

FixedThreadPool The characteristic of this kind of thread pool is that it is full of core threads , There are no non core threads , There is no timeout mechanism , There is no limit to the task size , The quantity is fixed , Even when idle , Threads are not recycled , Unless the thread pool is closed , It can also be seen from the construction method , There are only two parameters , One is the specified number of core threads , One is the thread factory ,keepAliveTime Invalid . Task queue adopts unbounded blocking queue LinkedBlockingQueue, perform execute Method time , The running thread did not reach corePoolSize Just create the core thread to execute the task , Otherwise, it will be blocked in the task queue , Get the task to execute when there is an idle thread . Because the thread pool has a fixed number of threads , And not recycled , Thread and thread pool life cycle synchronization , therefore It is suitable for tasks with fixed amount of tasks but long time consuming .

ScheduledThreadPool The number of core threads in this thread pool is fixed , Like and FixThreadPool It's kind of like , But its non core threads are unlimited , And non core threads will be recycled as soon as they are idle ,keepAliveTime It's also ineffective , Because the core thread will not be recycled , When the number of running threads does not reach corePoolSize When , Just create a new thread DelayedWorkQueue To take ScheduledFutureTask And then we go to the mission , Otherwise, add the task to DelayedWorkQueue,DelayedWorkQueue Will sort the tasks , Execute in the order of creating a new non core thread , Recycle after thread execution , Then the cycle . The task queue uses DelayedWorkQueue It's an unbounded queue , Delay the execution of queue tasks . Comprehensive, , This kind of thread pool It is suitable for performing scheduled tasks and repetitive tasks with specific fixed cycles .

SingleThreadPool As the name suggests, this thread pool is a thread pool with only one core thread , From the construction method , It can be executed separately , It can also be combined with the periodic thread pool . Its task queue is LinkedBlockingQueue, This is an unbounded blocking queue , Because there is only one thread in the thread pool , Just make sure that all tasks are executed sequentially in the same thread , This eliminates the need to deal with thread synchronization . This kind of thread pool It is applicable to scenarios where multiple tasks are executed sequentially .

3. What is a process ? What is thread ? What's the difference?

1、 A process is an execution of a program , It is the basic unit of system operation program . Processes are dynamic , The process by which a system runs a program even though a program is created from 、 Run to die . 2、 A thread is a smaller unit of execution than a process , Multiple threads can be generated during the execution of a process . Multiple threads of the same kind share the heap and method area resources . Each thread has its own program counter 、 Virtual machine stack 、 Native Method Stack . The system is generating a thread 、 Or when switching between threads , The burden is less than the process , therefore , Threads also become lightweight processes .

There can be more than one thread in a process , Multiple threads share the process's heap and method area (JDK1.8 Meta space after ) resources , But each thread has its own program counter 、 Virtual machine stack and Native Method Stack .

summary : Threads are smaller units of running divided into processes . The biggest difference between threads and processes is that they are basically independent , Threads are not necessarily , Because threads in the same process are likely to interact . Low thread execution cost , But it is not conducive to the management and protection of resources ; And the process is the opposite

4. The life cycle of a thread

  1. New state :    use new Keyword after creating a thread , The thread object is in the new state . Threads in a new state have their own memory space , By calling start() Method into ready state .
  2. Ready state :      In the ready state, the thread is ready to run , But it hasn't been assigned to CPU, In thread ready queue , Wait for the system to assign CPU. When the system selects a thread waiting to execute , It will go from ready to running , This action is called “CPU Dispatch ”.
  3. Running state       The thread in the running state executes its own run Code in method , Until waiting for a resource to block or complete anything and die . If there is no end of execution within a given time slice , It will be replaced by the system and returned to the ready state .
  4. Blocked state    Threads in a running state in some cases , If implemented sleep( sleep ) Method , Or wait for I/O Equipment and other resources , Will give way to CPU And temporarily stop running , Go into blocking mode .    A thread in a blocked state cannot enter the ready queue . Only when the cause of the blockage is removed , If it's time to sleep , Or wait I/O The device is free , The thread is ready , Wait in the ready queue again , After being selected by the system, continue execution from the original stop position .

5. Death state      The dead state is the last stage in the thread life cycle . There are three causes of thread death , One is that the running thread completes all its work ; The other is that the thread is forced to terminate , Such as through stop Method to terminate a thread 【 It is not recommended to use 】; Third, the thread throws an uncaught exception .

5. Threads sleep() and wait() The differences and similarities of methods

1、sleep() Method does not release lock ,wait() Method releases the lock 2、 Both can pause thread execution 3、wait Usually used for thread interaction / signal communication ,sleep Used to suspend execution 4、wait() After method is called , Thread will not wake up automatically , Need other thread to call on the same object notify() perhaps notifyAll() Method .sleep() After method execution , Thread will wake up automatically . Use wait() Thread will wake up automatically after timeout

6. Why call start() Method will execute run() Method , Why can't we call it directly run() Method

Create a thread (new Thead), The thread will enter the new state ; call start() After the method , Will start the thread and enter the ready state , When the thread is allocated to a time slice, it can run , Carry out operation status . start() Will perform the corresponding preparatory work of the thread , And then automatically run() Method ; If it is only executed separately run() Method , Will be able to run() Method as a main Thread to execute , It does not execute in a thread , Not multithreaded work .

call start Method can start a thread and put it into a ready state , and run It's just thread A normal method call of , Or execute in the main thread

7.synchronized keyword

synchronized Keyword is mainly used to solve the synchronization of accessing resources between multiple threads ,synchronized Keyword can ensure that only one thread can execute the decorated method or code block at any time

synchronized The three main ways to use keywords

  1. Decorated instance method : Lock the current object instance , Get the lock of the current object instance before entering the synchronization code
  2. Modified static method : Lock the current class , It will affect all object instances of the class
  3. Decorated code block : Specify the lock object , Lock a given object , Get the lock of the given object before entering the synchronization code base

synchronized Keywords added to static Static methods and synchronized The code block is for Class Class lock .synchronized Keyword is added to the instance method to lock the object

8. Synchronized and ReenTrantLock Comparison of

See the following links for specific learning , https://gitee.com/SnailClimb/JavaGuide/blob/master/docs/java/Multithread/synchronized.mdhttps://lixj.fun/archives/%E8%B0%88%E8%B0%88synchronized%E4%B8%8Ereentrantlock%E7%9A%84%E5%8C%BA%E5%88%AB?token=a4e096986aa04e1ebcd7e0d2348959ef

9. volatile keyword

1、java Memory model The thread saves the main memory variables to the local memory , Instead of reading and writing directly in main memory . This will cause a thread to change the value of a variable in main memory , The other process continues to use the value of its local memory copy , Cause data inconsistency .

To solve the above problems , You need to declare the variable as volatile, Get from main memory every time you use it

volatile The main function of is to ensure the visibility of variables , There is also the prevention of instruction rearrangement

10. synchronized and volatile The difference between

1、volatile Keyword is a lightweight implementation of thread synchronization , therefore volatile The performance will be better than synchronized Better .

2、volatile Can only be used for variables ,synchronized Can be used to decorate methods and code blocks . Used in actual development synchronized More scenes

3、 Multithreaded access volatile It won't block ,synchronized There could be a blockage

4、volatile Can guarantee the visibility of data , The atomicity of the data cannot be guaranteed .synchronized Both visibility and atomicity can be guaranteed

5、volatile It is mainly used to solve the visibility of variables between multiple threads ,synchronized It is mainly used to solve the synchronization of accessing resources between multiple threads

11. Thread pool related

Look at my previous articles , Java Thread pool in Runnable and Thread Compare

Copyright: use Creative Commons signature 4.0 International license agreement to license Links:https://lixj.fun/archives/ Note 4 - Multithreading

原网站

版权声明
本文为[Li_ XiaoJin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102054352145.html