Multi-thread synchronization

Source: Internet
Author: User

In multi-threaded programming, this type of resource simultaneously accessed by multiple threads is called a critical resource.
 
The Synchronized keyword is a modifier that can be used to modify methods or code blocks. Its function is: For the same object (not different objects of a class), when multiple threads call this method or code block at the same time, it must be executed once, that is, if two or more threads execute the code at the same time, if one thread has started to execute the code, the other thread must wait until the thread finishes executing the code.
Multi-threaded synchronization improves system security
 
Two manifestations of thread synchronization:
1. synchronous code block.
 
Synchronzied (Object lock ){
Code to be synchronized. (Which do not need to be synchronized)
}
 
2. synchronous functions.
 
The synchronzied keyword is added to the function. ,
The Synchronous Code block can use any object as the lock.
The synchronous function only uses one lock, that is, this.
Note: The lock used by the static synchronization function is the object of the class to which the function belongs. Class Name. class
Thread Synchronization Method in ticket sales system:
Package com. hbsi;
// Simulate the critical resource class
Class Tickets {
Publicinttickets;
Public Tickets (){
Tickets = 10;
}
Publicsynchronizedvoid action (String name ){
System. out. println (name + "grab the ticket" + tickets + ");
Tickets --;
}
}
// Data access thread
Class TicketsThread extends Thread {
Tickets t;
String name;
Public TicketsThread (Tickets t, String name ){
This. t = t;
This. name = name;
Start ();
}
@ Override
Publicvoid run (){
Try {
For (int I = 0; I <5; I ++ ){
T. action (name );
Thread. sleep (20 );
}
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
 
}
// Test the problem of multi-thread access
Publicclass TestMulThread2 {
Publicstaticvoid main (String [] args ){
// TODO Auto-generated method stub
Tickets t = new Tickets ();
TicketsThread d1 = new TicketsThread (t, "John ");
TicketsThread d2 = new TicketsThread (t, "Xiao Zhang ");
}
}
Running result:
John grabbed the 10th ticket.
John grabbed the 9th ticket
John grabbed the 8th ticket.
John grabbed the 7th ticket
John grabbed the 6th ticket.
John grabbed the 5th ticket
John grabbed the 4th ticket.
John grabbed the 3rd ticket
John grabbed the 2nd ticket.
John grabbed the 1st ticket
 
Thread synchronization code block in the ticket sales system:
Package com. hbsi;
 
 
Publicclass ticket1 implements Runnable {
Privateintticket= 100;
@ Override
Publicvoid run (){
// TODO Auto-generated method stub
// Object obj = new Object ();
While (true ){
Synchronized (this ){
If (ticket> 0 ){
Try {
Thread. sleep (100 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
System. out. println (Thread. currentThread (). getName () + "..." + ticket --);
} Else {
Break;
}
}
}

}
Publicstaticvoid main (String [] args ){
// TODO Auto-generated method stub
Ticket1 t = new ticket1 ();
Thread td1 = new Thread (t );
Thread td2 = new Thread (t );
Td1.start ();
Td2.start ();
}
}
 
Single-instance lazy thread synchronization:
Public class Single {
Privatestatic Single s = null;
PrivateSingle (){}
Publicstatic Single getInstance (){
If (s = null ){
Synchronized (Single. class)
{
If (s = null)
S = new Single ();
}
}
Return s;
}
}
After the thread is synchronized, the lazy security will be further improved.
 
Thread deadlock:
The main cause of deadlock is
Because the system resources are insufficient.
The process execution sequence is not appropriate.
Improper resource allocation.
If the system resources are sufficient, all process resource requests can be satisfied, and the possibility of deadlock is very low. Otherwise, a deadlock will occur due to competition for limited resources. Second, the process may run in different order and speed, and may also lead to deadlocks.
 
Four Conditions for deadlock
Mutual Exclusion condition: A resource can only be used by one process at a time.
Request and retention conditions: when a process is blocked by requesting resources, it will not release the obtained resources.
Non-deprivation condition: resources obtained by a process cannot be forcibly deprived before they are used.
Cyclic waiting condition: a type of cyclic waiting resource relationship is formed between several processes.
These four conditions are necessary for a deadlock. As long as a deadlock occurs in the system, these conditions must be met. As long as one of the above conditions is not met, no deadlock will occur.

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.