JAVA-multithreading (sorting)
Priority> 1 ~ 10
Thread Scheduling
OS:
Preemptible> threads with higher priority will replace the currently running threads
Non-preemptible> the current running thread is not replaced even if there is a thread with a higher priority.
JVM:
Green thread: the simplest thread processing model. For OS, there is only one process and one thread, so
Jvm must maintain the original information of the thread to be created ..
Daemon thread/non-daemon thread:
When the parent thread of the created thread dies, the daemon thread ends automatically instead of the daemon thread.
No.
Create thread
Implement the Runnable interface Thread class ThreadGroup class
Static Method
Int Thread. activeCount (); returns the number of active threads in the Thread group of the current Thread.
Thread. currentThread (); returns the current Thread
Void Thread. sleep (long );
Basic operations
1. Set the daemon/non-daemon attribute
SetDaemon (); specifies whether the thread is a daemon.
2. Start
Call the start () method and the system calls back the run () method.
3. Stop/suspend/recover a thread
Stop ()/suspend ()/resume ();
4. transfer control to other threads
Yield () generally refers to letting other threads with the same priority obtain the cpu time.
5. Change Priority
SetPriority ()
6. Wait for other objects
Obj. wait ()
7. Thread interruption
Interrupt ()> send the message of the interrupt thread
IsInterrupted ()> do not clear the flag. This method is an object method and returns whether the current thread is interrupted.
Thread. interrupted ()> returns the flag and clears it, indicating whether the current Thread is interrupted.
Synchronization object lock
The CPU allocation by threads is asynchronous, And the execution sequence of threads is not budgeted. When different threads access the same
Resource, it will cause the resource to be insecure. At the underlying layer, when each thread accesses the resource, it only accesses the resource
Cache value, different execution sequence leads to inconsistent cache resources in different time periods. java provides
Synchronized keyword: When a thread attempts to access the resource for the first time, it locks the resource until the thread completes access,
Other threads can access the resource. When the thread is interrupted to access the resource, other threads cannot access the resource.
Object. wait ();/object. Policy ();
Both functions must be used in the synchronized code block or function block.
When the wait method of the object is called, the thread is paused until the notify of the object is called.
Code is executed. When multiple wait methods of the object are called, the method that wakes up the thread will wake up the earliest call.
Wait thread. The system also provides the yyall () method to wake up all waiting objects.