Lock in Java5 1

Source: Internet
Author: User
Tags static class

This article can be used as a learning note for the Zhang Xiaoxiang-java multi-threading and concurrency Library advanced application.

A simple example of two threads, a constantly printing a, a continuously printing b

public class Locktest {public static void main (string[] args) {final Outputer outputer = new Outputer ();                    New Thread (New Runnable () {@Override public void run () {while (true) {                    try {thread.sleep (10); } catch (Interruptedexception e) {//TODO auto-generated catch block E.prin                    Tstacktrace ();                } outputer.output ("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");                }}). Start ();                    New Thread (New Runnable () {@Override public void run () {while (true) {                    try {thread.sleep (10); } catch (Interruptedexception e) {//TODO auto-generated catch block E.prin                    Tstacktrace (); }                    Outputer.output ("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");            The number of}//a is consistent with the number of B}}). Start ();            } Static class outputer{public void output (String name) {int len = name.length ();                try{for (int i=0;i<len;i++) {System.out.print (Name.charat (i));            } System.out.println (); }finally{}}}}


The final part of the result
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
B
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Why is that?
Very simple, at the time of output B, there is no output, a thread (the thread that prints a) has grabbed control, began to print a, and so on after a thread output A, and print a carriage return, the B thread to grab back the system control, print it last one of the remaining B.
To solve the above problem is simple:
    Static class outputer{public        synchronized void output (String name) {            int len = Name.length ();            //.....        }    }
In this way, we guarantee that the output method in the Outputer class is atomic and will not have two threads executing it at the same time.

Do we have a better way to do it in the example above?
Yes.
JAVA5 provides a more object-oriented technical class to solve the mutex problem between multiple threads-----lock.
Java.util.concurrent.locks Interface Lock
The core of lock technology is lock and its implementation class.

Basic Lock above example if you use a lock, the code is as follows
    Static class outputer{        lock lock = new Reentrantlock ();                public void output (String name) {            int len = Name.length ();            Lock.lock ();      Identity 1            try{for                (int i=0;i<len;i++) {                    System.out.print (Name.charat (i));                }                System.out.println ();            } finally{                Lock.unlock ();//ID 2            }        }
Thread A executes the lock on the identification 1 of the code above, and when thread A is outputting character A, thread B also executes to identity 1. Thread B is not able to obtain a lock at this time. It is blocked to identity 1 until the lock is released at identity 2 after thread A has finished printing. (Thread a thread B shared a lock, that is, lock lock = new Reentrantlock ())
In addition, why is the release lock of the logo 2 put in the Finally, you should understand it.
Read and Write

In the above problem, the body of the output (Len is the local variable inside the method, for each thread's own, non-interfering) is all mutually exclusive, it guarantees that at any time, only one thread executes the code that identifies 1 directly with identity 2.

But we have to realize: the operation of the common data can be divided into two categories, reading and writing.
When it comes to common resource operations, we should follow three main criteria:
1 When a thread writes to a resource, the other thread can neither read nor write to the resource.
2 when a thread reads a resource, other threads cannot write to the resource.
3 when a thread reads a resource, other threads can read the resource.
The one or two guideline guarantees the correctness of the system. The third criterion can improve the performance of the system. After all, it is possible for multiple threads to read a resource.
Look at the following examples of both reading and writing.
public class Readwritelocktest {public static void main (string[] args) {final Queue3 q3 = new Queue3 (); for (int i=0;i<3;i++) {new Thread () {public void run () {while (Tru                                            e) {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 multiple threads can read the data at the same time. public void Get () {try {System.out.println (Thread.CurrentThread (). GetName () + "is ready to read data!"            );            Thread.Sleep ((Long) (Math.random () *1000));      System.out.println (Thread.CurrentThread (). GetName () + "has read data:" + data);              } catch (Interruptedexception e) {e.printstacktrace (); }} public void put (Object data) {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 () + "have write data:" + data);        } catch (Interruptedexception e) {e.printstacktrace (); }    }}
The results are as follows
Thread-0 is ready to read data!
Thread-1 is ready to write data!
Thread-2 is ready to read data!
Thread-3 is ready to write data!
Thread-4 is ready to read data!
Thread-5 is ready to write data!
Thread-0have Read Data:null
Thread-0 is ready to read data!
Thread-3 have write data:5280
Thread-3 is ready to write data!
Thread-1 have write data:5839
Thread-1 is ready to write data!
Thread-4have Read data:5839
We can see that there is a complete confusion in reading and writing in writing.

Let's try a two method plus synchronized results as follows
Thread-0 is ready to read data!
Thread-0have Read Data:null
Thread-5 is ready to write data!
Thread-5 have write data:7931
Thread-5 is ready to write data!
Thread-5 have write data:9564
Thread-5 is ready to write data!
Thread-5 have write data:1203
Thread-5 is ready to write data!
Thread-5 have write data:8870
Thread-4 is ready to read data!
Thread-4have Read data:8870
Thread-3 is ready to write data!
Thread-3 have write data:9334
Thread-3 is ready to write data!
Thread-3 have write data:2680
Thread-3 is ready to write data!
Thread-3 have write data:9948
Thread-3 is ready to write data!
Thread-3 have write data:375
Thread-2 is ready to read data!
Read and write completely mutually exclusive, read the time do not write, write when do not read. Meet the one or two guidelines.

Read-write lock in order to implement the criterion three, there are read and write locks in Java5.
Java.util.concurrent.locks Interface Readwritelock
There are two methods of Readwritelock
Lock Readlock () Returns the lock used for reading.
Lock Writelock () Returns the lock used for writing.
Once you have two locks, you can call lock and unlock methods.
Generally use its subclass reentrantreadwritelock to generate Readwritelock
Its signature is as follows:
public class Reentrantreadwritelock extends Object implements Readwritelock, Serializable
See how it's Used
Class queue3{Private Object data = null;//share data, only one thread can write the data, but multiple threads can read the data at the same time.    Readwritelock rwl = new Reentrantreadwritelock ();        public void Get () {Rwl.readlock (). Lock ();            try {System.out.println (Thread.CurrentThread (). GetName () + "be ready to read data!");            Thread.Sleep (20);                    System.out.println (Thread.CurrentThread (). GetName () + "has read data:" + data);        } catch (Interruptedexception e) {e.printstacktrace ();        }finally{rwl.readlock (). Unlock ();        }} public void put (Object data) {Rwl.writelock (). Lock ();                                try {System.out.println (Thread.CurrentThread (). GetName () + "be ready to write data!");            Thread.Sleep (20);                    This.data = data;                            System.out.println (Thread.CurrentThread (). GetName () + "have write data:" + data); } catch (Interruptedexception E) {e.printstacktrace ();        }finally{rwl.writelock (). Unlock (); }    }}
The results are as follows
Thread-5 have write data:7329
Thread-0 is ready to read data!
Thread-0 have read data:7329
Thread-1 is ready to write data!
Thread-1 have write data:1361
Thread-2 is ready to read data!
Thread-4 is ready to read data!
Thread-0 is ready to read data!
Thread-2 have read data:1361
Thread-2 is ready to read data!
Thread-4 have read data:1361
We can see that the write of thread 1 is completely mutually exclusive.

The read of thread 2 4 0 can be done synchronously.

This is the simplest example of a read-write lock, and in the next section we look at a slightly more complex example of putting a read lock and a write lock into a method.

Thanks GLT

Lock in Java5 1

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.