Example of lock usage in Java multithreaded programming _java

Source: Internet
Author: User

A lock is a tool that controls the access of multiple threads to a shared resource. Typically, a lock provides exclusive access to a shared resource. Only one thread can acquire a lock at a time, and all access to shared resources requires the lock to be acquired first. However, some locks may allow concurrent access to shared resources, such as readwritelock (maintaining a pair of related locks, one for read-only operations and another for write operations).

1, Lock provides an unconditional, polling, timed, interruptible Lock acquisition operations, all lock and Unlock methods are explicit.

  interruptedexception;
  Boolean Trylock (); A timed and polling lock acquisition pattern
  Boolean trylock (Long timeout,timeunit unit) throws interruptedexception;
  void unlock (); Unlock
  Condition newcondition ();
}

2, Reentrantlock implementation of the lock interface, compared with synchronized, Reentrantlock to deal with the use of the lock provides more flexibility.
3. Using the lock interface's canonical form requires that the lock Lock.unlock () be released in the finally block. If the lock-guarding code throws an exception outside of a try block, it will never be freed.

The following simulates lock usage: Suppose there are two threads (a thread, B thread) to call the print (String name) method, a thread is responsible for printing the ' Zhangsan ' string, and the B thread is responsible for printing the ' Lisi ' string.
1. When no lock is added for the print (String name) method, a thread is generated and the B thread has been executed, and the printed name appears as follows.

2, when a lock is added to the print (string name) method, the B thread executes the print (string name) method, or the synchronization effect, after a execution completes.

Package com.ljq.test.thread;
Import Java.util.concurrent.locks.Lock;
 
Import Java.util.concurrent.locks.ReentrantLock;  /** * with lock instead of synchronized * * @author Administrator * */public class Locktest {public static void main (string[)
  args) {new locktest (). Init ();
    private void Init () {final Outputer outputer = new Outputer ();
            A thread new thread (new Runnable () {@Override public void run () {while (true) {try {
          Thread.Sleep (10);
          catch (Interruptedexception e) {e.printstacktrace ();
        } outputer.output ("Zhangsan");
 
    }}). Start ();
            b Thread new Thread (new Runnable () {@Override public void run () {while (true) {try {
          Thread.Sleep (10);
          catch (Interruptedexception e) {e.printstacktrace ();
        } outputer.output ("Lisi");
 
  }}). Start ();
 
 } Static class Outputer {lock lock = new Reentrantlock ();
      /** * Print Character * * @param name */public void output (String name) {int len = name.length ();
      Lock.lock ();
        try {for (int i = 0; i < len; i++) {System.out.print (Name.charat (i));
      } System.out.println ();
      finally {Lock.unlock ();

 }
    }
  }
}

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.