Java Threads: Synchronizing

Source: Internet
Author: User

The concept of a synchronization

Thread synchronization is a breach of data that prevents multiple threads from accessing a data object.

For example: Two threads Threada, threadb all manipulate the same object Foo object, and modify the data on the Foo object.

  Myrunnable.java

1  PackageThread;2  Public classMyrunnableImplementsrunnable{3     PrivateFoo foo=NewFoo ();4      Public Static voidMain (string[] args) {5Myrunnable r=Newmyrunnable ();6Thread Ta=NewThread (R, "Thread-a");7Thread tb=NewThread (R, "Thread-b");8 Ta.start ();9 Tb.start ();Ten     } One      Public voidrun () { A          for(inti=0;i<3;i++){ -              This. Fix (30); -             Try{ theThread.Sleep (1); -             } -             Catch(interruptedexception e) { - e.printstacktrace (); +             } -System.out.println (Thread.CurrentThread (). GetName () + ": Value of the current Foo object =" +foo.getx ()); +         } A     } at      Public intFixinty) { -         returnFoo.fix (y); -     } -}
View Code

  Foo.java

1  PackageThread;2  Public classFoo {3     Private intx=100;4      Public intGetX () {5         returnx;6     }7      Public intFixinty) {8x=x-y;9         returnx;Ten     } One}
View Code

  Operation Result:

1 thread-a: The value of the current Foo object =402 thread-b: The value of the current Foo object =403 thread-a: The value of the current Foo object =-204 Thread-b: The value of the current Foo object =-505 thread-a: The value of the current Foo object =-806 thread-b: The value of the current Foo object =-80
View Code

The result shows that the output value is obviously unreasonable. The reason is that two threads do not have control over the Foo object and modify the data caused by the modifier. Therefore, the access to Foo should be limited, and only one thread can access it at a time.

1. Synchronization method

Thread synchronization is a means of guaranteeing multi-threaded secure access to competing resources. There are two things to do in synchronizing the specific Java code:

1, the competitive access to the resources identified as private;

2. Synchronize the code that modifies the variable, using the Synchronized keyword synchronization method or code. (for synchronized, you can only mark non-abstract methods, and you cannot identify member variables.) )

To demonstrate the use of synchronization methods, a credit card account was built, initially with a credit limit of 100w, and then simulated overdraft, deposit and other operations. Obviously the bank account user object is a competitive resource, and a number of concurrent operations are account method oper (int x), of course, you should add synchronization on this method, and set the account balance as a private variable, prohibit direct access.

  Banktest.java

1  PackageThread;2 3  Public classBanktest {4      Public Static voidMain (string[] args) {5User u=NewUser ("small Two", 100);6MyThread t1=NewMyThread ("Thread 1", u,20);7MyThread t2=NewMyThread ("Thread 2", u,-60);8MyThread t3=NewMyThread ("Thread 3", u,-80);9MyThread t4=NewMyThread ("Thread 4", u,-30);TenMyThread t5=NewMyThread ("Thread 5", u,32); OneMyThread t6=NewMyThread ("Thread 6", u,21); A T1.start (); - T2.start (); - T3.start (); the T4.start (); - T5.start (); - T6.start (); -     } + } - classMyThreadextendsthread{ +     PrivateUser u; A     Private intY=0; atMyThread (String name,user u,inty) { -         Super(name); -          This. u=u; -          This. y=y; -     } -      Public voidrun () { in u.oper (y); -     } to } + classuser{ -     PrivateString Code; the     Private intCash; *User (String Code,intCash) { $          This. code=Code;Panax Notoginseng          This. cash=Cash; -     } the      PublicString GetCode () { +         returnCode; A     } the     /** + * Business Method -      * @paramx Add x million $      * */ $       Public synchronized voidOperintx) { -          Try{ -Thread.Sleep (10L); the               This. cash+=x; -System.out.println (Thread.CurrentThread (). GetName () + "run result, add" +x+ ", the current balance is:" +cash);WuyiThread.Sleep (10L); the          } -          Catch(interruptedexception e) { Wu e.printstacktrace (); -          } About      } $       PublicString toString () { -          return"user{" + "code=" + code + ", cash=" + Cash + '} '; -      } -}
View Code

The result is:

1 Thread 1 run result, increase 20, current balance is:2 thread 2 run result, increase-60, the current balance is: 3 thread 6 run result, increase 21, the current balance is: Bayi4 Thread 5 run result, increase 32, current balance is: 1135 thread 4 run result, increase-30, current balance is: 6 thread 3 run result, increase-80, current balance is: 3

However, if you remove the Sync keyword synchronized, the result is:

1 Thread 2 run result, increase-60, current balance is:2 thread 6 run result, increase 21, current balance is: 13 thread 4 run result, increase-30, current balance is: 34 thread 5 run result , add 32, the current balance is: 35 thread 1 run result, increase 20, current balance is: 6 thread 3 run result, increase-80, current balance is:-20

Obviously wrong, multiple threads concurrently access the competing resource U and modified the properties of U. Visibility of the importance of synchronization.

2. Synchronous block

Sometimes, synchronization blocks have a better effect than synchronous methods. On the basis of the previous example, the Oper method was changed, and the synchronization method changed to synchronous block mode.

   Banktest.java

1  Public voidOperintx) {2          Try{3Thread.Sleep (10L);4              synchronized( This){5                   This. cash+=x;6System.out.println (Thread.CurrentThread (). GetName () + "run result, add" +x+ ", the current balance is:" +cash); 7              }8Thread.Sleep (10L);9          }Ten          Catch(interruptedexception e) { One e.printstacktrace (); A          } -}

The result is the same as the previous example. The specific change thought is:

 Public int GetX () {2    return x + +;  // Synchronization Method 3 }4 with publicint  GetX () {6   synchronized (this) {     7         return x;   Non-synchronous method 8     }9}

Attention:

When using synchronized, you should avoid using the sleep or yield method in the synchronized method or synchronized block. Because the synchronized block occupies the object lock, you rest so that other threads can only wait. This is inefficient. Similarly, it doesn't make sense to call the yield method within the Synchronizer block to make the CPU resources, because you are hogging the lock and other resources are inaccessible.

3, static method synchronization

To synchronize a static method, you need a lock with the entire class object, which is the Class (Xxx.class), such as:

1 public static synchronized int SetName (String name) {2   xxx.name=name;  equivalent to 5 public static int SetName () {6   synchronized (Xxx.class) {7 xxx.name= } 9}   

4. When to synchronize

1. When multiple threads access mutually exclusive (exchangeable) data, the data should be protected synchronously, ensuring that two threads do not change it at the same time.

2. Data that can be changed in non-static fields, usually accessed by non-static methods.

3. Data that can be changed in static field is accessed by static method.

Java Threads: Synchronizing

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.