- A thread is a different execution path within a program.
- the state of the thread: Create the Thread object first, and then call the start () method to enter the ready state. (But not immediately, wait until the CPU is scheduled to enter the running state, and then may be running when the problem, into the blocking state.) Could have been terminated.
- Some common methods:
Sleep (): Specifies how long the thread sleeps
Yield (): give the CPU to other threads
Notify (): Wake -Up thread
Notifyall (): Wake up All Threads
SetPriority (): Set Priority
- Two ways to implement threading:
Inheritance thread Threading class or implementing the runnable interface, it is recommended to implement the interface method, because java can not inherit more. Then rewrite their Run () method , which is similar to the execute () method inside the struts2 , Are all base class definitions that need to be implemented inside.
- thread synchronization:synchronized (this) {
code blocks that need to be synchronized;
}
Alternatively: Create a synchronization method by adding synchronized directly to the method.
Only the current code block runs out of other objects to access the current synchronization fast.
It is important to notethat the valid range of synchronized is only the current object or method under his control, and other non- synchronized objects, the method can still be accessed normally.
- Deadlock: When a thread needs an object to execute, but the object is locked by another thread, and the thread needs an object to execute, and the object is locked by you, it will cause a deadlock. The solution is to expand the block of code you want to synchronize.
- the difference between Wait () and sleep () :
First Wait () is the method of the object class, and sleep () is the thread class. Wait () is equivalent to letting go of the lock, other objects can access your original locked part, and sleep () is still locked, not accessible.
Simple understanding of threading