Usage of synchronized keyword

Source: Internet
Author: User

Synchronized is used to lock a method or block, only the object that obtains the lock of the object or block can execute the code inside, otherwise it will block there, wait for the lock to be released, and then get the lock to continue execution. For example, the following code to simulate ticketing:

/**
* Simulated Sale tickets
 *
* @author Administrator
 *
 */
Public class Synchronizeddemo {

Public static void Main (string[] args) {
Runnable Runnable = new Runnable () {
int count = ten;
Public void Run () {
While (true) {
if (count <= 0) {
Break ;
} else {
count--;// Mark 1
System.out.println (Thread.CurrentThread (). GetName ()
+ ": also remaining" + Count + "ticket");
try {
Thread.Sleep (+);
} catch (Exception e) {
e.printstacktrace ();
                        }
                    }
                }
            }
        };
thread T1 = new Thread (runnable);
thread t2 = new Thread (runnable);
T1.start ();
T2.start ();
    }
}
Operation Result:

Thread-0:9 Tickets left
Thread-1:8 Tickets left
Thread-1:6 Tickets left
Thread-0:6 Tickets left
Thread-0:4 Tickets left
Thread-1:4 Tickets left
Thread-1:3 Tickets left
Thread-0:3 Tickets left
Thread-1:2 Tickets left
Thread-0:1 Tickets left
Thread-0:0 Tickets left

If the current count=8, when T1 run out of tag 1 (red tag in the code) count=7, it happens that the thread's time slice ran out. At this time T2 began to run, when the T2 run the Mark 1 when the count=6, and then output the value of count, will output the remaining 6, at this point, when the T2 is finished, T1 began to mark 1 after the execution, output count of the value, will output the remaining 6, this output of the above results.

Workaround:

If you join the synchronized code block, you can solve the above problem, the core code is as follows

Synchronized (this) {//Tag 2
count--;
System.out.println (Thread.CurrentThread (). GetName () + ": also remaining" + Count + "ticket");

}

Where this represents the address of the object to be locked.

Operation Result:

Thread-0:9 Tickets left
Thread-1:8 Tickets left
Thread-0:7 Tickets left
Thread-1:6 Tickets left
Thread-1:5 Tickets left
Thread-0:4 Tickets left
Thread-1:3 Tickets left
Thread-0:2 Tickets left
Thread-0:1 Tickets left
Thread-1:0 Tickets left

This is the correct result, this is because when the T1 to execute tag 2 (red in the code is marked), the first will determine whether the address is locked, if not locked, will execute coount--, and at this time the T1 is run out, T2 began to execute, when T2 execution to the Mark 2, First to determine whether the address is locked, found that the address has been locked, so T2 wait for the release of the lock, when the T2 time slice run out, T1 began to continue execution, at this time then the last execution of the position execution, output count value, and then release the lock, when the T1 time slice used up, T2 found that the address of the lock was released, so T2 get the lock, and then go in to execute ... And so on The results will be output correctly.

The synchronized code block works only if the address pointed to by this is the same, such as changing the type of count to the address of the Integer,synchronized code block passing in count, the core code is as follows:

Integer count = 10;

Synchronized (count) {
count--; Mark 3
System.out.println (Thread.CurrentThread (). GetName ()
+ ": also remaining" + Count + "ticket");
}

Result output:

Thread-1:8 Tickets left
Thread-0:9 Tickets left
Thread-1:6 Tickets left
Thread-0:6 Tickets left
Thread-0:5 Tickets left
Thread-1:4 Tickets left
Thread-0:2 Tickets left
Thread-1:2 Tickets left
Thread-0:1 Tickets left
Thread-1:0 Tickets left

Result Analysis:

If COUNT=4,T1 now lock the address of count, after executing the tag 3 count=3, assuming that the T1 time slice run out, and at this point T2 began to execute, T2 first to determine whether the address of the count is locked, found at this time the address of count is not locked, This is because the T1 lock is count=4 address, and at this time T2 determine whether the address of count=3 is locked, and the count=3 address is not locked, so T2 will execute code block code, after executing the tag 3 count=2, and then output the remaining 2 tickets, When the T2 time slice is used up, the T1 starts to carry out the output still remaining 2 tickets, therefore appears above phenomenon. This is because the address of count is changed, so the parameter passed to synchronized is an immutable address, such as the byte code of the class.

Usage of synchronized keyword

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.