Analysis of thread and synchronization

Source: Internet
Author: User



Daemon Threads
Typically, the application behind the scenes is that the daemon is guarded by the end of the thread, even if the daemon thread is not finished, then it will end.


Thread-Local Variables: object property data security issues when solving multi-threaded sharing of the same object
Threadlocal Get by Get


Thread pool: The container of threads can help us to create threads. Executorservice


Description: Thread class, the main class for creating threads
Thread CurrentThread () Gets the threading object where the current code resides
String GetName () Gets the name of the thread
Main thread Name: main
Child thread Name: thread-number, numbering starting from 0
void SetName (String?name) sets the name of the thread
Long GetId () Gets the ID of the thread
Boolean isAlive () is active
Thread.state getState () returns the thread state
Thread.State.NEW Create State
Thread.State.RUNNABLE ready state-operational status
Thread.State.TERMINATED End State
Thread.State.BLOCKED Blocking State
Thread.State.TIMED_WAITING Sleep State
Thread.State.WAITING Wait Status
Blocking state
Main thread Name: main
Child thread Name: thread-number, numbering starting from 0
Thread.State.NEW Create State
Thread.State.RUNNABLE ready state-operational status
Thread.State.TERMINATED End State
Thread.State.BLOCKED Blocking State
Thread.State.TIMED_WAITING Sleep State
Thread.State.WAITING Wait Status
void Setdaemon (Boolean?on) marks the thread as a daemon (background) thread or user thread
Thread.Sleep (long Millis) thread into wait state (timed_wating)
The Thread.yield () thread withdraws, giving the execution opportunity to the same or higher priority thread, but then still may continue to execute
The Void join () thread joins, the current thread enters the waiting state, and when the called thread finishes running, the current thread reverts to the runnable state
void setpriority (int newpriority) Set precedence
int getpriority () Gets the priority level
Runnable interface
Description: A thread-body interface that only has thread-executed tasks and does not have threading capabilities
Function: Provides shared data for multiple threads of the same program code
public void Run () abstract method
Description: A thread-body interface that only has thread-executed tasks and does not have threading capabilities
Function: Provides shared data for multiple threads of the same program code
public void Run () abstract method


1. Each thread in a process has a piece of its own memory in the stack
Multi-Threading and stack
1. Each thread in a process has a piece of its own memory in the stack
2. Only when the thread finishes executing its own task code will it release its own memory
3. The process ends only when all threads in the process have ended
2. Only when the thread finishes executing its own task code will it release its own memory
3. The process ends only when all threads in the process have ended


Line Cheng


When using notify, be sure to use the while to avoid errors


Synchronized used a pessimistic lock.
Lock optimistic Lock.


Synchronized (object) {}
After use, the lock is released
A separate description of the lock using the lock interface


Create a subclass of lock Reentrantlock
Use lock instead of our synchronous code block
The code that needs to be synchronized is placed between lock and unlock,


Condition is using await () signal () Signalall ()




Description: A security issue for resolving shared data between threads
Mutual exclusion Lock
Function: Introduce the concept of object mutex in Java to ensure the integrity of shared data operation
Description: Each object corresponds to a tag that can be called a "mutex", which guarantees that only one thread can access the object at any one time
Keyword: synchronized, used to add mutexes to objects
How to Solve
When a thread gets the CPU and executes multiple statements that share data, other threads cannot participate, and only the thread executes all statements that share data, and other threads can participate in the execution
Free Theme
When a thread gets the CPU and executes multiple statements that share data, other threads cannot participate, and only the thread executes all statements that share data, and other threads can participate in the execution
Thread synchronization
Description: A security issue for resolving shared data between threads
Mutual exclusion Lock
Function: Introduce the concept of object mutex in Java to ensure the integrity of shared data operation
Description: Each object corresponds to a tag that can be called a "mutex", which guarantees that only one thread can access the object at any one time
Keyword: synchronized, used to add mutexes to objects
Three kinds of locking method
1. Synchronous non-static method
Format: public synchronized void Method1 () {}
Description: Synchronized is placed in a method declaration, indicating that the entire method is a synchronous method, locking the This object
If one thread enters the method, and the other thread wants to use any of the current synchronization methods of this object, it must wait for the previous thread to finish executing the synchronization method
2. Synchronous static method
Format: public synchronized static void Method1 ()
Description: Synchronized is placed in the static method declaration, which indicates that the class object is locked
If one thread enters the method and other threads want to use any of the synchronous static methods in the current class, they must wait for the previous thread to finish executing the synchronization method, and the execution of the other non-synchronous methods and non-static synchronous methods is unaffected.
3. Synchronizing code blocks
Synchronize this:
Synchronized (this) {//this is locked and any other code block to lock this is blocked.
Code that needs to be synchronized;
}
Synchronizing obj:
Synchronized (obj) {//obj is locked and any other block of code to lock obj is blocked.
Code that needs to be synchronized;
}
Description: Synchronized placed before an object to restrict execution of a piece of code
The drawbacks of thread synchronization
Threads that cannot enter the synchronization code block will repeatedly interpret the lock, reducing the program's performance
Conditions to be met for using synchronization
1. At least two threads in sync
2. Use the same lock
Avoid deadlocks
Because thread 1 locks resource A to wait for resource B, thread 2 locks resource B to wait for resource A, two threads are waiting for the resources they need, and those resources are locked by another thread, you wait for me, I wait for you, no one is willing to give up resources, so the deadlock will produce
Three kinds of locking method
1. Synchronous non-static method
Format: public synchronized void Method1 () {}
Description: Synchronized is placed in a method declaration, indicating that the entire method is a synchronous method, locking the This object
If one thread enters the method, and the other thread wants to use any of the current synchronization methods of this object, it must wait for the previous thread to finish executing the synchronization method
2. Synchronous static method
Format: public synchronized static void Method1 ()
Description: Synchronized is placed in the static method declaration, which indicates that the class object is locked
If one thread enters the method and other threads want to use any of the synchronous static methods in the current class, they must wait for the previous thread to finish executing the synchronization method, and the execution of the other non-synchronous methods and non-static synchronous methods is unaffected.
3. Synchronizing code blocks
Synchronize this:
Synchronized (this) {//this is locked and any other code block to lock this is blocked.
Code that needs to be synchronized;
}
Synchronizing obj:
Synchronized (obj) {//obj is locked and any other block of code to lock obj is blocked.
Code that needs to be synchronized;
}
Description: Synchronized placed before an object to restrict execution of a piece of code
The drawbacks of thread synchronization
Threads that cannot enter the synchronization code block will repeatedly interpret the lock, reducing the program's performance
Conditions to be met for using synchronization
1. At least two threads in sync
2. Use the same lock
Avoid deadlocks
Because thread 1 locks resource A to wait for resource B, thread 2 locks resource B to wait for resource A, two threads are waiting for the resources they need, and those resources are locked by another thread, you wait for me, I wait for you, no one is willing to give up resources, so the deadlock will produce


Communication between Threads:


Description: The tasks performed by multiple threads are different, but the resources for the operations are the same
Producer Consumer Model
The problem of producers (Producer) and consumers (Consumer)
The producer will give the product to the clerk (clerk), and the consumer takes the product from the clerk, the clerk can only hold a fixed quantity of product at a time, if the producer produces too much product, the clerk calls the producer to wait a moment, if the store has the vacancy to put the product to inform the producer to continue the production; The clerk will tell the consumers to wait, if there is a product in the store and then notify the consumer to take away the product.
The problem of producers (Producer) and consumers (Consumer)
The producer will give the product to the clerk (clerk), and the consumer takes the product from the clerk, the clerk can only hold a fixed quantity of product at a time, if the producer produces too much product, the clerk calls the producer to wait a moment, if the store has the vacancy to put the product to inform the producer to continue the production; The clerk will tell the consumers to wait, if there is a product in the store and then notify the consumer to take away the product.
Understanding Waiting and waking

Wait () in the object class causes the current thread to wait until other threads call the Notify () method of this object or the Notifyall () Wake method
Thread Waits
Wait () in the object class causes the current thread to wait until other threads call the Notify () method of this object or the Notifyall () Wake method
The Notify () method in the object class wakes up a single thread that waits on this objects monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary.
Thread Wakeup
The Notify () method in the object class wakes up a single thread that waits on this objects monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary.
The Notifyall () method in the object class wakes up all the threads that are waiting on this objects monitor.
The Notifyall () method in the object class wakes up all the threads that are waiting on this objects monitor.
Note: Wait (), notify (), and Notifyall () Three methods can only be called in a method or code block that is synchronized (synchronized)


The thread stops:


1. If the thread's run () method executes a recurring loop, you can provide a "tag" to control whether the loop continues execution
2. For the executing thread, interrupt () cannot interrupt the execution of the thread, but can get the flag that the thread is interrupted: thread.interrupted () gets true, and after the call, the interrupt flag is cleared (to false)
3. If the thread enters a blocking state because it is executing join (), sleep () or wait (), to stop it, you can use interrupt (), the program throws a Interruptexception exception and is caught by the catch () clause and processed
4, if the program is blocked because of input/output wait, basically must wait for the input/output action to complete before leaving the blocking state. The interrupt () method cannot be used to leave the thread out of the run () method and to leave, only by throwing an exception.


For the operation of the lock:
The operation of the lock is implicit before jdk1.5
Synchronized (object)//Acquire Lock
{
Code that needs to be synchronized
}//Release Lock
jdk1.5 A separate description of the lock using the Lock interface---object-oriented
Free Theme
Lock interface
Description: JDK1.5 provides a synchronous lock operation interface
Condition newcondition () Gets the condition of the lock and facilitates the operation of the thread's state or condition
Lock () Get locks
Unlock () Release lock
Synchronized (object)//Acquire Lock
{
Code that needs to be synchronized
}//Release Lock
involves core interfaces and classes
Lock interface
Description: JDK1.5 provides a synchronous lock operation interface
Condition newcondition () Gets the condition of the lock and facilitates the operation of the thread's state or condition
Lock () Get locks
Unlock () Release lock
Reentrantlock class
Implementation class for Interface lock
int Getholdcount ()
int Getqueuelength ()
int Getwaitqueuelength (Condition Condition)
Boolean hasqueuedthreads () determines if multiple threads exist in the lock's wait pool
Boolean haswaiters (Condition c) determines the thread in the lock's wait pool that contains the Condition condition
Conditon interface
Description: Provides state operations for the thread of the lock, such as waiting and waking
Await () wait
Signal () Wake-up
Signalall () Wake up all
Reentrantlock class
Implementation class for Interface lock
int Getholdcount ()
int Getqueuelength ()
int Getwaitqueuelength (Condition Condition)
Boolean hasqueuedthreads () determines if multiple threads exist in the lock's wait pool
Boolean haswaiters (Condition c) determines the thread in the lock's wait pool that contains the Condition condition
Conditon interface
Description: Provides state operations for the thread of the lock, such as waiting and waking
Await () wait
Signal () Wake-up
Signalall () Wake up all
1. Create a child class object for lock
2. Call the Lock object's newcondition () to create a thread state control object
3. Place the code that needs to be synchronized between lock () and unlock ()
Use steps
1. Create a child class object for lock
2. Call the Lock object's newcondition () to create a thread state control object
3. Place the code that needs to be synchronized between lock () and unlock ()
4, in the use of Wait (), notify () and other places, change into a condition object related methods
Attention
1. Only one lock object can exist between multiple threads
2, in order to avoid deadlock, generally put the unlocked position in the finally statement
3, for wait-notify state conversion should produce two condition objects to control
4, in the use of Wait (), notify () and other places, change into a condition object related methods
Attention
1. Only one lock object can exist between multiple threads
2, in order to avoid deadlock, generally put the unlocked position in the finally statement
3, for wait-notify state conversion should produce two condition objects to control


Local variables for the thread:


Classes involved: java.lang.ThreadLocal
Role: A data security issue that is used to troubleshoot object properties when multiple threads share the same object.
1) Each Threadlocal object is like an entire building's mailbox, and each thread can only open one of its own mailboxes. This mailbox can only be placed on one object.
Description
1) Each Threadlocal object is like an entire building's mailbox, and each thread can only open one of its own mailboxes. This mailbox can only be placed on one object.
2) Essentially, there is a map in the Threadlocal class that stores a copy of the variable for each thread. And you don't need to know what the key is (actually the current thread). There is no mistake in using local variables for other threads.
2) Essentially, there is a map in the Threadlocal class that stores a copy of the variable for each thread. And you don't need to know what the key is (actually the current thread). There is no mistake in using local variables for other threads.




Background Daemon Thread:


Description: A thread running in the background that serves other threads
Set Method: Setdaemon (Boolean B) set a thread as a background thread
1, often for the end of the task of the aftermath of processing, a typical background thread is the timers timer thread
Role
1, often for the end of the task of the aftermath of processing, a typical background thread is the timers timer thread
2. Background threads have a lower priority than other threads
3. If no "user thread" is running, the JVM exits and the daemon thread is automatically terminated
2. Background threads have a lower priority than other threads
3. If no "user thread" is running, the JVM exits and the daemon thread is automatically terminated




General rules for multithreaded programming
1. If two or more threads modify an object, the method that executes the modification is defined as synchronized, and if the object update affects the read-only method, then the read-only method is defined as synchronous.
2, do not misuse synchronization. If different methods within an object are not accessing the same data, do not set the method to synchronized
3. If a thread must wait for an object state to change, then he should wait inside the object, not outside. He can call a synchronized method and let the method call Wait ().
4. Whenever a method returns a lock on an object, it should call Notifyall () to allow other threads in the wait queue to have an opportunity to execute.
5. Remember that wait () and notify ()/notifyall () are methods of the object class, not the thread class. Looking closely at each call to the wait () method, there is a corresponding notify ()/notifyall () method, and they are all used for the same object.




General rules for multithreaded programming:


1. If two or more threads modify an object, the method that executes the modification is defined as synchronized, and if the object update affects the read-only method, then the read-only method is defined as synchronous.
2, do not misuse synchronization. If different methods within an object are not accessing the same data, do not set the method to synchronized
3. If a thread must wait for an object state to change, then he should wait inside the object, not outside. He can call a synchronized method and let the method call Wait ().
4. Whenever a method returns a lock on an object, it should call Notifyall () to allow other threads in the wait queue to have an opportunity to execute.
5. Remember that wait () and notify ()/notifyall () are methods of the object class, not the thread class. Looking closely at each call to the wait () method, there is a corresponding notify ()/notifyall () method, and they are all used for the same object.


static void sleep (long milliseconds) is set to make the running thread sleeping within milliseconds
Throws an exception Throws interruptedexception () thread hibernation is the best way to help all threads get resources
The thread wakes up automatically after sleep, returning to the ready state is not a running state
Sleep specifies that the shortest time to run after hibernation cannot be guaranteed to start running after expiration
is the static method of intelligently controlling the current thread


The priority of the thread, the higher the opportunity, the lower the chance, the less the absolute
The maximum is 10 min is 1 default is 5
Using SetPriority ()
GetPriority ()


The join () method thread of the thread's merge current thread waits for the thread to finish executing
Static yield (0 The current thread concessions will only yield once the next time is which thread is not necessarily
How to break a thread
Interrupt () The interrupt method of the thread changed the flag of the interrupt false--true
Static Boolean interrupted () whether the state returned by the interrupt is flag but there is a method for checking it out.




The principle of implementation is to lock an object


How synchronization is implemented: Synchronous code block synchronized (lock) {} method code is automatically unlocked after execution completes, you can make any object obj = new objects
Synchronized ()
This locks the current object to declare the current object as a lock
Can lock a string
Run-time Locks
Static data calls are used at runtime locks
The synchronous method is preceded by the method with synchronized
Synchronous static method locks the This object
Synchronous static method Locking is Xxx.class




Multithreading requires a synchronization mechanism


Data security:
Synchronized () {} Using a synchronous block of code
The type can be any object
The current object this can be a static object at the same time
There is also a method of using synchronous method to pay attention to the particle size


Multi-threaded sharing of data when multiple, one thread to perform the operation of shared data if it has not been completed, the other threads are preempted to the CPU then the process will be the data is not secure a CPU then the other CPU can only wait until the thread completes the execution.
The advantage of using a synchronous block of code is to put the shared data inside, but the performance needs to be constantly accessed to see if the lock has been released.


Conditions are met when using synchronization:
Minimum of two threads
Use the same lock









Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Analysis of threads and synchronization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.