Implementation of Java thread synchronization __java

Source: Internet
Author: User
Tags finally block mutex semaphore

thread sharing restricted resources
1, basically all concurrency patterns in the resolution of threading conflict, are used serializing access to shared resourcesProgram that allows only one task to access a shared resource at a given time; this is usually done by adding a lock statement to the code, often called Mutex (mutex)

2, Implicit lock synchronizationusing the Synchronized keyword
1) shared resources are generally in the form of objects memory fragment, but can also be a file, input/output port, printer;2 to control access to shared resources, first you want to wrap it into an objectYou then mark all methods (or blocks of code) that access the resource as synchronizedalso mark the shared domain as private; 3) Sample code
1, the whole method of synchronization
class demo{
     private int shareresource;
     Public synchronized void Method1 () {  shareresource + +;  }
     Public synchronized void Method2 () {  shareresource-;  }
}
2, the method needs to synchronize the place to synchronize
class demo{
     private int shareresource;
     public void Method1 () {
          System.out.println ("method1 start");
          Synchronized (this) {
               Shareresource + +; 
           } 
          System.out.println ("Method1 end"); 
     }
     public void Method2 () {
          System.out.println ("method2 start");
          Synchronized (this) {
               shareresource-;
           }
          System.out.println ("Method2 end");
     }

4) for a specific objectIn terms of its scope all synchronized methods share a lock; 5 Each Access critical shared resource method must be synchronized, otherwise other methods will ignore the lock;

3, the explicit lock synchronization: Use Lock to lock
1) java.util.concurrent.Locks in Java SE5You can explicitly define the mutex mechanism; 2 Sample code
Class demo{
     private int shareresource;
     Private lock lock = new Reentrantlock ();
     public int method{
          lock.lock ();
          try{
               Shareresource + +;
               return shareresource;
          } finallly{
               Lock.unlock ();
          }
     Place the synchronized block in a try-finally block, and return must be in a try block to ensure that the unlock does not occur prematurely, exposing the data to the second task;




3 The amount of code that uses synchronized implicitly locks is less, lock objects are usually used in some special cases, such as: ① use synchronized can not attempt to acquire a lock, and the final acquisition lock fails to throw only an exception, can not do any cleanup work; ② tries to acquire the lock for a period of time and then releases it;
Class demo{
     Private Reentrantock lock = new Reentrantlock ();
     public void Method1 () {
          Boolean result = Lock.trylock ();   Lock is in idle state only when called,
          try{
               System.out.println (result);
          finally{
               if (result)
                    lock.unlock ();
          }
     }
     public void Method2 () {
          Boolean result = false;
          try{result
               = Lock.trylock (2,timeunit.seconds); 
                At the time of the call, lock is idle in 2seconds, and the thread is not interrupted in the period of the class, to acquire the lock;
          }catch (interruptedexception e) {
               System.out.println ( result);
          } finally{
               if (result)
                    lock.unlock ();
          }
     }






4, to simulate a mutex by limiting the amount of 1 license signals(The number of threads used to restrict access to shared resources when semaphores)
  Class task{
     semaphore semaphore = new semaphore (1);
     public void Xmethod () {
           try{
                 semaphore.acquire ();
                 statement;
           } catch (Interruptedexception ex) {
           }finally{
                 semaphore.release ();
           }
     }
  }




5※, using atomic class instead of synchronized mutex synchronization
1) Atomic sexatomic operation does not require synchronous control, atomic operation can not be interrupted by the thread scheduling operation, once the operation has started, it must be executed before the possible context switches, and can be written using the specific No Locks2) atomicity can be applied to "simple operations" above all basic types except long and double, and for operations such as reading and writing basic variables other than long and double, it is guaranteed that they will be treated as inseparable operations to manipulate the memory;
3) Atomic class: Java SE5 introduced special atomic variables such as Atomicinteger,atominclong,atomicreference,They provide the following forms of atomic conditional update operations: These classes are adjusted to use on some modern processors available, and at the machine level of atomicity, generally applied to performance tuning;
boolean compareandset (expectedvalue,updatevalue);Current value = = expected value, set the value to the given value in atomic mode int getandadd (int delta);Adds the given value to the current value in the form of an atom int getandset (int delta);Sets the current value to the given value in atomic form int get (); void Set (int newvalue);such as: Atomicinteger i = new Atomicinteger (1024);   I.compareandset (1024,2048); This operation is thread-safe 4) Sample code
Import java.util.concurrent.atomic.*;
     Class demo{Private Atomicinteger count = new Atomicinteger (0);
     public int GetValue () {return count.get ();} public void Method1 () {count.getandadd,} public void Method2 () {count.getandderement ();//count++} public Vo ID method3 () {count.getandincrement ();//count--}//test public static void Main () {demo demo = new D
          EME ();
          Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (New Runnable () {public void run () {while (true) {D
                         Emo.method1 ();
                    System.out.println (Demo.getvalue ());
           }
               }
          }); Exec.execute (New Runnable () {public void run () {while (true) {D
                         EMO.METHOD2 ();
                    System.out.println (Demo.getvalue ());
         }
               } }); Exec.execute (New Runnable () {public void run () {while (true) {D
                         Emo.method3 (); System.out..
                    println (Demo.getvalue ());
     }
               }
          }); }//atomic operation of the data, the operation can be synchronized without using synchronized;




6. Critical area 1) Critical Area (critical section)/synchronous control block: Sometimes you just want multiple threads to access part of the code inside the method at the same time, rather than the whole method, which is the critical section of the code block; synchronized (syncobject) { statements; } 2 before entering the synchronization control block, you must obtain a lock on the SyncObject object, if another thread has acquired the lock, it is not possible to enter the critical section until the lock is released; 3 use synchronous control blocks instead of synchronizing the entire method , the time performance of multiple task Access objects can be significantly improved. 4 synchronized block must be given an object on which to synchronize(This is the object of synchronized (this) when used more reasonably); Sometimes you have to synchronize on another object, and you must ensure that all related tasks are synchronized on the same object. at this point two synchronized control blocks are independent of each other, they are not blocked because of each otherExample:
Resolution limit: An object can only acquire one synchronous lock ———— enable two tasks to simultaneously enter the same object
class demo{
     Private Object syncobject = new Object ();
     Public synchronized void Method1 () {while
          (true) {
               println ("method1 ()");
               Thread.yield ();
          }
     public void Method2 () {
          synchronized (syncobject) {while
               (true) {
                    println ("Method2 ()");
                    Thread.yield ();
    }} Test public
     static void main () {
          Final Demo demo = new Demo ();
          New Thread () {public
               void run () {
                    demo.method1 ()}
          }
          DEMO.METHOD2 ();
     }




7. Thread Local Storage threadlocal1) In addition to the above methods of using mutex synchronization, the second way to create conflicts on shared resources by placing task children : To eradicate the sharing of variables;2 Threads in Java Local storage is an automated mechanismyou can create different storage for each thread that uses the same variableSave, you can use java.lang.ThreadLocal to achieve; 3) Instance code
Class demo{
     private static threadlocal<integer> value = new threadlocal<integer> ();
     Value.set (0);
     public static void Mian (string[] args) {
          Executorservice executor = Executors.newcachedthreadpool ();
          for (int i=0;i<5;i++) {
               executor.execute (new Runnable () {public
                    void run () {     
                         value.set (Value.get () +i) ;
                         System.out.print (Value.get () + ",");
                    }
               }
          TimeUnit.SECONDS.sleep (3);
          Executor.shutdown ();
     }
/*output:
     0,1,2,3,4
///Only use Set (), get () to modify and access the treadlocal data;






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.