1. Threads:
A. Origin: Single task os--multi-tasking OS
B. Process: Each process corresponds to an application that allocates independent memory space
C. Thread: A thread is a separate execution branch within a process
D. Features: Shared content address space, lower switching costs
2. Thread creation and startup
A. Method one: (Thread)
① inherits the thread class, overriding the Run method--run method is only responsible for determining what this thread is going to do
Public class extends thread{ publicvoid run () { }}
② Open Thread, call the Start method-the method allocates resources for the thread and then automatically calls This.run ()
New MyThread (); Mt.start (); // Open Thread
③ if the Run method is called-no error, but only normal method call, no new thread is opened
B. Method two: (Runnable)
① implements the Runnable interface, overriding the Run method--run method is only responsible for determining what this thread is going to do
Public class Implements runnable{ publicvoid run () { }}
② creates a thread object that passes in the implementation class object of the Runnable interface
Call Start () of the Thread object
Newnew Thread (YT); Th.start ();
3. Thread Status
A. Process: ① new State (new Thread () object)--ready state (call Start (), but start () before calling run ()--run State (Start (), call Run ())--Death State (Run () method ends, resource recycling cleanup)
② Interrupt state: In the running state, the thread is not getting CPU execution for various reasons
B. Five reasons for interrupt status:
① Thread Priority: Thread priority of 10 levels, up to 10, minimum 1
A higher priority is only a greater chance of being executed, and it does not mean that a low priority
Th.setpriority (th.setpriority) (thread.max_priority) ;
② blocking: Causes the thread to break due to input/output (for example: Scanner)
③ sleep: The Sleep method of thread
Th.sleep (+); // number of milliseconds to sleep
④ wait and wake: The Wait () and notify () method for Object
⑤ Hang: The Yield () method of Thread
4. Sync Lock
A. Keyword: synchronized
B. Meaning: When multiple threads access the same resource, it is possible that the resource data is confusing.
To ensure that the resource can only be used by one thread at a time, and then handed over to the next thread after use, we use synchronous technology.
C. The implementation of synchronization:
① Synchronization method: Add sync keyword on resource synchronized
Public synchronized void Show (String name) {}
② Sync block: Use synchronized on the thread that invokes the resource
synchronized (this. rs) { the. Rs.show (this. GetName ());}
Java Multi-Threading programming