Collection
zero Useful+1
zero

Thread scheduling

Computer terminology
The computer usually has only one CPU and can only execute one machine instruction at any time thread Only get CPU To execute instructions. So called multithreaded Concurrent operation In fact, it means that from a macro perspective, each thread obtains the CPU usage rights in turn and executes its own tasks. In the running pool, there will be multiple ready threads waiting for the CPU, JAVA virtual machine One of its tasks is to schedule threads. Thread scheduling refers to allocating CPU usage rights to multiple threads according to a specific mechanism.
Chinese name
Thread scheduling
By the way, help
computer
Procedure
JAVA virtual machine
scheduling model
Time sharing scheduling model and Preemptive scheduling model

brief introduction

Announce
edit
There are two scheduling models: time-sharing scheduling model and Preemptive Scheduling model.
Time sharing scheduling model means that all thread It is also easy to understand that you can obtain the right to use the CPU in turn and evenly allocate the CPU time slice occupied by each thread.
Java virtual machine The preemptive scheduling model refers to giving priority to the threads with high priority in the runnable pool to occupy the CPU. If the threads in the runnable pool have the same priority, then randomly select a thread to occupy the CPU. The running thread will run until it has to abandon the CPU.

Reason for abandoning CPU

Announce
edit
One thread The CPU will be abandoned for the following reasons.
one Java virtual machine Let the current thread temporarily abandon the CPU and turn to the ready state, so that other threads can get running opportunities.
2 The current thread is blocked for some reason
3 Thread ends running
It should be noted that thread scheduling is not cross platform. It depends not only on the Java virtual machine, but also on the operating system. In some operating systems, as long as the running thread does not encounter a block, it will not give up the CPU; In some operating systems, even if the thread does not encounter blocking, it will give up the CPU after running for a period of time to give other threads a chance to run.
Java's thread scheduling is time-sharing. After multiple threads are started at the same time, it cannot guarantee that each thread will get an equal CPU time slice in turn.
If you want to explicitly let one thread give another a chance to run, you can take one of the following measures.
Adjust the priority of each thread
Let the running thread call the Thread.sleep method
Let the running thread call the Thread.yield method
Let the running thread call the join method of another thread
Thread switch: not all thread switches need to enter kernel mode