Thread Lock Technology

Source: Internet
Author: User
Tags static class
  Lock is more object-oriented than synchronized in the traditional threading model, and locks, like locks in life, should also be an object. Code snippets executed by two threads to achieve the effect of synchronizing mutexes, they must use the same lock object, which is in the internal method of the class that represents the resource being manipulated, not in the thread code.
Import Java.util.concurrent.locks.Lock;
 
Import Java.util.concurrent.locks.ReentrantLock;
   public class Locktest {public static void main (string[] args) {new locktest (). Init ();
      public void init () {Outputer outputer = new Outputer (); New Thread (New Runnable () {@Override public void run () {while (true) {try
                {Thread.Sleep (10);
                catch (Interruptedexception e) {e.printstacktrace ();
            } outputer.output ("Zhangxiaoxiang");
     
      }}). Start (); New Thread (New Runnable () {@Override public void run () {while (true) {try
                {Thread.Sleep (10);
                catch (Interruptedexception e) {e.printstacktrace ();
            } outputer.output ("Liwenfei");
      }
         }  
      ). Start (); /** * There is a thread-safe problem * */* class outputer{public void output (String name) {int len = NA
         Me.length ();
         for (int i=0; i<len; i++) {System.out.print (Name.charat (i));
      System.out.println ();//newline}}*/static class outputer{Lock lock = new Reentrantlock ();
         public void output (String name) {int len = name.length ();
         Lock.lock (); try{//use try is to make sure that the code inside is open for the lock for (int i=0; i<len; i++) {System.out.print (i
            ));
         System.out.println ();//linefeed}finally{lock.unlock (); }/** * Method Two: Synchronize the code to sync all synchronously * Use synchronized in the method and do not use synchronized inside, otherwise it is easy to appear deadlock *
         /Public synchronized void Output2 (String name) {int len = name.length (); for (int i=0; i<len; i++) {System.out.print (Name.charat (i)); System.out.println ();//newline}/** * If this synchronization method is static, then to ensure that no matter who invokes the synchronization method, the lock object is the same, * that
         The lock can only be a byte-code object for the current class, that is, Outputer.class * @param name/public static synchronized void Output3 (String name) {
         int len = Name.length ();
         for (int i=0; i<len; i++) {System.out.print (Name.charat (i)); } System.out.println ()//NewLine}}}
Lock is divided into read lock and write lock, multiple read lock is not mutually exclusive, read lock and write lock mutually exclusive, write lock and write lock mutually exclusive. This is controlled by the JVM itself, and you just have to do the proper lock. If your code is read-only, many people can read at the same time, but not at the same time, then read the lock; If your code modifies the data and only one person is writing and cannot read the data at the same time, write the lock. In short read the time to read the lock, write the lock when writing. Improve performance.
Import Java.util.Random;

Import Java.util.concurrent.locks.ReentrantReadWriteLock;
		public class Readwritelocktest {public static void main (string[] args) {final Queue3 q3 = new Queue3 (); for (int i = 0; i < 3; i++) {The new Thread () {@Override public void run () {while (true) {Q3.get (
					);
			}}.start ();
					New Thread () {public void run () {while (true) {Q3.put (New Random (). Nextint (10000));
			}
				};
		}.start (); }} class Queue3 {private Object data = NULL;//shared data, only one thread can write the data, but can have multiple threads to read private Reentrantreadwritelock RWL

	= new Reentrantreadwritelock ();
		public void Get () {Rwl.readlock (). Lock ();
			try {System.out.println (Thread.CurrentThread (). GetName () + "be ready to read data!");
			Thread.Sleep ((Long) (Math.random () * 1000));
		System.out.println (Thread.CurrentThread (). GetName () + "Hava Read data:" + data);
		catch (Exception e) {e.printstacktrace (); finally {Rwl.readlock (). Unlock ();
		Use finally no matter what happens, be sure to release the lock} public void put (Object data) {Rwl.writelock (). Lock ();
			try {System.out.println (Thread.CurrentThread (). GetName () + "be ready to write data!");
			Thread.Sleep ((Long) (Math.random () * 1000));
			This.data = data;
		System.out.println (Thread.CurrentThread (). GetName () + "Hava writed data:" + data);
		catch (Exception e) {e.printstacktrace ();
		finally {Rwl.writelock (). Unlock (); }
	}
}

In the JDK API Java.util.concurrent.locks.ReentrantReadWriteLock class, there is a pseudo code example of a cache design:
Class Cacheddata {
   Object data;
   Volatile Boolean cachevalid;
   Reentrantreadwritelock rwl = new Reentrantreadwritelock ();

   void Processcacheddata () {
     rwl.readlock (). Lock ();
     if (!cachevalid) {
        //must release read lock before acquiring write lock
        rwl.readlock (). Unlock ();
        Rwl.writelock (). Lock ();
        Recheck state because another thread might have acquired
        /   write lock and changed the state before we did.
        if (!cachevalid) {
          data = ...
          Cachevalid = true;
        }
        Downgrade by acquiring read lock before releasing write lock
        Rwl.readlock (). Lock ();
        Rwl.writelock (). Unlock (); Unlock write, still hold read
     } use

     (data);
     Rwl.readlock (). Unlock ();
   }
 

The idea of caching:













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.