lesson x

Let's understand the first problem first:
After the thread is created, it does not run.
After the creation, the start() method is called, and it does not run immediately, but becomes a runnable state.
All threads are in a runnable state, sitting in the waiting seat, waiting for the CPU master to call, those who are called to run, and those who are not called to wait.

After being selected by the CPU master, the person who is occupying the CPU is in the running state. But the CPU won't hold you for long, considering the mood of the threads on the other waiting seats. The CPU will frequently call in the thread in the waiting seat and let it run.
The thread that has been replaced from the CPU becomes operational again, waiting to be called again.

Calling the thread's yield() method is equivalent to learning from Lei Feng and telling the CPU master that this thread is not in a hurry. When calling the thread next time, other threads will be given priority.


After running the thread, the state changes to aborted.
If the thread is running and an exception occurs, the thread will also end and the state will change to aborted.


During the running process of the thread, it may be necessary to wait for other threads.
For example, if a thread occupies a synchronized object, it will take a lock.
Then when other threads need to access this object, they will need to wait. After it is used up, the lock is released, and other threads can continue to enter the runnable state.

Calling the join() method of a thread is equivalent to forcibly waiting for a thread to complete first. It is usually used to explicitly know that a thread must be executed before it can be executed.

You can call the Thread.sleep() method to force yourself to wait for a while and enter the runnable state again.


If multiple threads call a method on an object at the same time, or modify an object's properties, this can cause problems.
So we need a syntax that allows a certain method of an object, or a certain piece of code, only one thread can come in at the same time. The rest are waiting. This is synchronization, synronized.


But this brings another problem, that is, if you enter a synronized thread, during the running process, you need to obtain a certain condition to continue. And the thread that can change this condition happens to be waiting to enter the synronized, which will lead to a deadlock situation where A waits for B to open, and B waits for A to open.
In the synroized code block, the lock can be released by calling the wait() method of the lock object, so that other threads that want to enter the synroized get a chance to run. When other threads are almost running, the notify() method can be called to wake up other waiting threads.







Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326905322&siteId=291194637