Java multi-thread programming trap summary 2

Source: Internet
Author: User

Trap 7: Use the static synchronization method correctly

Java language rules: any thread enters the synchronization method. Before synchronizing a code block, you must first obtain the synchronization method and synchronize the synchronization monitor corresponding to the code block. For a synchronous code block, the program must display the specified synchronization monitor for it; for Synchronous non-static methods, the synchronization Monitor of this method is this-that is, the Java object that calls this method; for static synchronization methods, the synchronization Monitor of this method is not this, but the class itself.

Class synchronizedstatic implements runnable {
Static Boolean flag = true;
Public static synchronized void test0 () {// The synchronization monitor is the class itself
For (INT I = 0; I <1000; I ++ ){
System. Out. println ("test0:" + thread. currentthread (). getname ()
+ "" + I );
}
}
Public void test1 (){
Synchronized (this) {// The synchronization monitor is this, that is, the Java object that calls this method.
For (INT I = 0; I <1000; I ++ ){
System. Out. println ("test1:" + thread. currentthread (). getname ()
+ "" + I );
}
}
}
Public void run (){
If (FLAG ){
Flag = false;
Test0 ();
} Else {
Flag = true;
Test1 ();
}
}
Public static void main (string ARGs []) throws interruptedexception {
Synchronizedstatic Ss = new synchronizedstatic ();
New thread (SS). Start ();
Thread. Sleep (1 );
New thread (SS). Start ();
}
}

Running result:
Test0: thread-0 244
Test1: thread-1 7
Test0: thread-0 245
Test1: thread-1 8
Test0: thread-0 246
Test1: thread-1 9
Test0: thread-0 247
Test1: thread-1 10
Test1: thread-1 11
Test1: thread-1 12
Test0: thread-0 248
Test1: thread-1 13
Test0: thread-0 249
Test0: thread-0 250


The running result shows that the static synchronization method can be executed simultaneously with the synchronization code block with this as the synchronization monitor. Because the two synchronization monitors are different, the former locks the synchronizedstatic class, and the latter locks the object referenced by the SS variable, so the program can switch between the two threads. If you change the test1 () method as follows:

Public void test1 ()

{

Synchronized (<span style = "color: # ff0000"> synchronizedstatic. Class </span>)

{// The same synchronization monitor as the static method
For (INT I = 0; I <1000; I ++)

{

System. Out. println ("test1:" + thread. currentthread (). getname () + "" + I );

}
}
}

Running result:

Test0: thread-0 995
Test0: thread-0 996
Test0: thread-0 997
Test0: thread-0 998
Test0: thread-0 999
Test1: thread-1 0
Test1: thread-1 1
Test1: thread-1 2
Test1: thread-1 3
Test1: thread-1 4

Results: The static synchronization method and the synchronization code block with the current class as the synchronization monitor cannot be executed simultaneously.

Trap 8: Do not synchronize Boolean Constants

In Java, the synchronized statement can implement multi-thread concurrency. With the synchronous code block, JVM ensures that only one thread can own the Lock of an object at a time. The lock mechanism enables multiple threads to securely access critical resources.
The Synchronous Code is written as follows:

Object OBJ = new object ();
...
Synchronized (OBJ ){
// Todo: access critical resources
}

Java's multithreading is always full of traps. If we use boolean as the synchronized object, there may be two situations:

I. Locking an object means that different objects are actually synchronized.

Private volatile Boolean istrue = false;
Publich void amethod (){
...
Synchronized (istrue ){
Istrue =! Istrue;
// Todo: access critical resources
Istrue =! Istrue;
}
...
}

Check that the above Code is correct. Because synchronized (istrue) is used, only one thread can access critical resources at a time, but this is not the case. The two constants "false" and "true" correspond to two different objects. When istrue changes, different threads may synchronize different objects. Java auto-boxing changes false to boolean. False, and true to boolean. True (this also indicates that the result is the same if false is changed to boolean. False ). Write the following test code for the above case:

Public class booleantest {
Private volatile Boolean istrue = Boolean. False; // use false here.
Public void amethod (){
For (INT I = 0; I <10; I ++ ){
Thread t = new thread (){
Public void run (){
Synchronized (istrue ){
Istrue =! Istrue;
System. Out. println (thread. currentthread (). getname () + "-istrue =" + istrue );
Try {
Double ran = 1000 * Math. Random ();
Thread. Sleep (ran. intvalue ());
} Catch (interruptedexception e ){}

If (! Istrue) system. Out. println (thread. currentthread (). getname () + "-oh, no! ");

Istrue =! Istrue;
}
}
};
T. Start ();
}
}
Public static void main (string... ARGs ){
Booleantest bt = new booleantest ();
Bt. amethod ();
}
}

Run the above Code and you will see "-oh, no! ", Indicating that different threads enter the synchronized code block at the same time.

2. Assume that different objects are synchronized, but they are actually an object.

Sometimes we may want to synchronize multiple objects. If Boolean is used as the synchronized object, it is very likely that the two synchronization blocks that should have no relationship use the lock of the same object. Example:

Private volatile Boolean logical lean = Boolean. False;
Private volatile Boolean anotherboolean = false;
Public void amethod (){
...
Synchronized (synchronized lean ){
// Todo: access critical resource 1
}
...
}
Public void anothermethod (){
...
Synchronized (anotherboolean ){
// Todo: access critical resources 2
}
...
}

Assume that the original amethod and anothermethod will be called by two groups of unrelated threads respectively. However, because Boolean. False and false point to the same object, access to critical resource 2 may be blocked by critical resource 1 (and vice versa ).

The preceding two cases indicate that when using a synchronization block, you do not need to use a Boolean object as the synchronized object. Otherwise, unexpected problems may occur or future code modifications may cause traps.

We can also see that any synchronization of constants is risky. To synchronize a Boolean object, you must use the new operator to create a Boolean object.

Original article: http://johnshen0708.iteye.com/blog/1393620

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.