Synchronous monitor: Synchronous Code block, synchronous method, and synchronous Monitor

Source: Internet
Author: User

Synchronous monitor: Synchronous Code block, synchronous method, and synchronous Monitor

If multiple threads access shared resources, the shared resources may be insecure when one thread does not process the business and another thread enters.

 

Daily example: A and B have the same bank account, A uses the passbook to get the money at the counter, and B uses the cash machine to get the money. There are two key steps to withdraw money:

    (1) Determine whether the balance of money in the account is greater than the amount of money obtained

(2) If the amount is greater than the amount of money obtained, the final remaining balance of the account = balance-the amount of money obtained.

If there is no thread synchronization, we assume that in this case, this account has a total of 1000 yuan.

    (1) When a B gets 600 yuan at the same time, the thread where A is located executes the first step above to judge that the amount of money obtained is less than the existing balance, and the CPU time slice is used up.

(2) When B comes in to the first step, it also executes the judgment. Because A only completes the first step and does not perform the subtraction, the existing balance is still 1000 yuan.

(3) The subtraction is completed during the CPU allocation time. In this case, the account balance is 1000-600 = 400. 600 RMB is retrieved successfully.

(4) The last step A follows is to perform the subtraction operation. The account balance is-200 = 400-600.

Here, I just want to explain why the bank allows you to do this, unless the bank is yours.

In short, banks cannot make this happen, so our great sages will think of thread synchronization, which is actually very simple. You can also think of it. If the two steps are completed at the same time and cannot be separated, the problem will be solved.

 

The following describes how to synchronize code in JAVA:

Concept:Synchronization MonitorIs a common java object. If a thread obtains the same synchronization monitor, other threads cannot obtain it. It seems that there is only one key in the door and it cannot be copied. If a person takes it into the door, others can only wait outside. You can enter the room only after you get it.

If the following code does not perform thread synchronization (Synchronous Code block, synchronization method, and synchronization lock), the result is as follows:

Thread-1 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-0 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-0 ====== do the subtraction operation, take out the cash ======
Thread-1 ====== do the subtraction operation, take out the cash ======

Obviously, the two steps of thread 1 are not completed at the same time.

 

The following methods can be completed in two steps at the same time.

1. synchronous code block:

Public class ThreadTest {

Public static void main (String [] args ){
Thread t1 = new Thread1 (); // Thread 1
Thread t2 = new Thread1 (); // Thread 2
T1.start ();
T2.start ();
}
}

Class Thread1 extends Thread {

@ Override
Public void run (){
Super. run ();
Try {

BeTested B = new BeTested ();// In this example, the synchronization monitor obj is shared by the thread, and the two threads use two different objects. It does not affect the result.
B. beTested (this );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}

Class BeTested {
Static Object obj = new Object ();;
Public void beTested (Thread t) throws InterruptedException {
   Synchronized (obj ){//Obj is the synchronization monitor.
System. out. println (t. getName () + "------ determine whether the amount of money obtained exceeds the balance ------");
T. sleep (1000 );//If there is no synchronization, it is obvious that the two steps cannot be completed in the same thread and in the same time slice.
System. out. println (t. getName () + "====== do the subtraction operation, take out the cash ==== ");
   }
}
}

The execution result is as follows:

Thread-0 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-0 ====== do the subtraction operation, take out the cash ======
Thread-1 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-1 ====== do the subtraction operation, take out the cash ======

Note: The selection of synchronization monitor objects is critical. To select an object shared by a thread, for example, obj in the above example, it is modified statically. If there is no static modification, different synchronization monitors (not the same object) are used ), equivalent to two keys.

(If obj = "aaaa" can be synchronized without static modification, it is because the same string object in the constant pool referenced by this obj is not recommended)

 

2. Synchronization Method (non-static method)

Change the above two classes to the following, and the class where the main method is located remains unchanged.

Class Thread1 extends Thread {

  Static BeTested B = new BeTested (); // In this method, the same object must be modified in static mode.
@ Override
Public void run (){
Super. run ();
Try {
B. beTested (this );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}

Class BeTested {
Static Object obj = new Object ();;
PublicSynchronizedVoid beTested (Thread t) throws InterruptedException {
System. out. println (t. getName () + "------ determine whether the amount of money obtained exceeds the balance ------");
T. sleep (1000 );
System. out. println (t. getName () + "====== do the subtraction operation, take out the cash ==== ");
}
}

The execution result is as follows:

Thread-0 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-0 ====== do the subtraction operation, take out the cash ======
Thread-1 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-1 ====== do the subtraction operation, take out the cash ======

Note: Because the synchronization monitor used in the synchronization method cannot be specified, the default object used to call this method, that is, this. Therefore, static modification is also required to synchronize the modified part of the code block in Thread1 compared to that in Example 1. That is to say, the same object must be used.

 

3. Synchronization Method (static method)

Change the above two classes to the following, and the class where the main method is located remains unchanged.

Class Thread1 extends Thread {

@ Override
Public void run (){
Super. run ();
Try {
     BeTested B = new BeTested (); // each thread uses a different object.
B. beTested (this );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}

Class BeTested {
Static Object obj = new Object ();;
PublicStatic synchronizedVoid beTested (Thread t) throws InterruptedException {
System. out. println (t. getName () + "------ determine whether the amount of money obtained exceeds the balance ------");
T. sleep (1000 );
System. out. println (t. getName () + "====== do the subtraction operation, take out the cash ==== ");
}
}

The execution result is as follows:

Thread-0 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-0 ====== do the subtraction operation, take out the cash ======
Thread-1 ------ determine whether the amount of money obtained exceeds the balance ------
Thread-1 ====== do the subtraction operation, take out the cash ======

Note: In synchronous static methods, the synchronization monitor is the object of this class rather than the object of this class. Therefore, compared to the modified part of the code block synchronized in example 2 in Thread1, static modification is not required. It does not matter if it is not the same object. This class is shared by itself.

 

Summary: When performing thread synchronization in the above methods, pay attention to the synchronization monitor object you are using. It must be shared.

 

Note: The Synchronous lock is also used to implement thread synchronization. This article will not discuss it.

 

Related Article

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.