To explain the thread blocking usage of Locksupport classes in Java multithreaded programming _java

Source: Internet
Author: User
Tags static class

Locksupport is the basic thread blocking primitive used to create locks and other synchronization classes.
The role of Park () and Unpark () in Locksupport is to block and unblock threads, and park () and Unpark () do not encounter "deadlocks that may be caused by thread.suspend and Thread.Resume."
Because Park () and Unpark () have a licensed presence, the contention between the thread that calls the park () and another thread that tries to Unpark () will remain active.

Basic usage
The Locksupport is very similar to the two-dollar semaphore (only 1 licenses are available), and if the permission is not already in use, the current thread acquires permission and continues execution, and the current thread blocks if the license has been used, waiting for permission to be obtained.

public static void Main (string[] args)
{
   locksupport.park ();
   System.out.println ("block.");
}

Running the code, you can find that the main thread has been blocked. Because the license is occupied by default, the call to Park () is not licensed, so it enters a blocking state.

The following code: first release the license, and then obtain permission, the main thread can terminate normally. Locksupport License acquisition and release, generally corresponds to, if multiple Unpark, only one park will not have any problems, the result is that the license is available.

public static void Main (string[] args)
{
   Thread thread = Thread.CurrentThread ();
   Locksupport.unpark (thread);//Release License
   Locksupport.park ();//Get License
   System.out.println ("B");
}

Locksupport is not reentrant, and if a thread calls Locksupport. Park () 2 times in a row, then the thread is bound to block forever.

public static void Main (string[] args) throws Exception
{
 thread thread = Thread.CurrentThread ();
 
 Locksupport.unpark (thread);
 
 System.out.println ("a");
 Locksupport.park ();
 System.out.println ("B");
 Locksupport.park ();
 System.out.println ("C");
}

The code prints out A and B and does not print C because the thread cannot get permission to deadlock when the second call to park.

Now let's look at the responsiveness of Locksupport to interrupts

public static void T2 () throws Exception
{
 thread t = new Thread (new Runnable ()
 {
  private int count = 0;
    @Override public
  Void Run ()
  {
   Long start = System.currenttimemillis ();
   Long end = 0;

   while ((End-start) <= 1000)
   {
    count++;
    End = System.currenttimemillis ();
   }

   System.out.println ("After 1 second.count=" + count);

  Waiting may permit
   locksupport.park ();
   SYSTEM.OUT.PRINTLN ("Thread over." + Thread.CurrentThread (). isinterrupted ());

 T.start ();

 Thread.Sleep ();

 Middle thread
 t.interrupt ();

 
 System.out.println ("main over");
}

The end thread prints out the thread over.true. This means that a thread can respond to an interrupt request (the interrupt state is set to true) if it is blocked by calling park, but does not throw a interruptedexception.

Locksupport Function List

Returns a Blocker object provided to the most recent park method call that has not been unblocked, or null if the call is not blocked.
static Object getblocker (thread t)
/\ For thread scheduling, disables the current thread unless the license is available.
static void Park ()
//For thread scheduling, disables the current thread until the license is available.
static void Park (Object blocker)
//disables the current thread for thread scheduling, waiting for the specified wait time, unless the license is available.
static void Parknanos (Long Nanos)
//For thread scheduling, disables the current thread before the license is available, and waits up to the specified wait time.
static void Parknanos (Object blocker, long Nanos)
//For thread scheduling, disables the current thread until the specified time limit, unless the license is available.
static void Parkuntil (long deadline)
//For thread scheduling, disables the current thread until the specified time limit, unless the license is available.
static void Parkuntil (Object blocker, long deadline)
//If the license for a given thread is not yet available, make it available.
static void Unpark (thread thread)


Locksupport sample
Compare the following example 1 and sample 2 to get a clearer idea of the usage of locksupport.
Example 1

public class WaitTest1 {public

  static void Main (string[] args) {

    Threada ta = new Threada ("ta");

    Synchronized (TA) {//synchronized (TA) gets the sync lock for object Ta
      try {
        System.out.println (Thread.CurrentThread (). GetName () + "Start Ta");
        Ta.start ();

        System.out.println (Thread.CurrentThread (). GetName () + "block");
        Main thread waits for
        ta.wait ();

        System.out.println (Thread.CurrentThread (). GetName () + "continue");
      } catch (Interruptedexception e) {
        e.printstacktrace ();

  }}} Static class Threada extends thread{public

    Threada (String name) {
      super (name);
    }

    public void Run (a) {
      synchronized (this) {/) Gets the sync lock for the current object SYSTEM.OUT.PRINTLN by synchronized (this)
        Thread.CurrentThread (). GetName () + "wakup others");
        Notify ();  Wake up the waiting thread on the current object}}}


Example 2

Import Java.util.concurrent.locks.LockSupport;

public class LockSupportTest1 {

  private static Thread mainthread;

  public static void Main (string[] args) {

    Threada ta = new Threada ("ta");
    Gets the main thread
    mainthread = Thread.CurrentThread ();

    System.out.println (Thread.CurrentThread (). GetName () + "Start Ta");
    Ta.start ();

    System.out.println (Thread.CurrentThread (). GetName () + "block");
    Main thread blocking
    Locksupport.park (mainthread);

    System.out.println (Thread.CurrentThread (). GetName () + "continue");
  }

  Static class Threada extends thread{public

    Threada (String name) {
      super (name);
    }

    public void Run () {
      System.out.println (Thread.CurrentThread (). GetName () + "wakup others");
      wake-up "Main thread"
      Locksupport.unpark (Mainthread);}}


Run Result:

Main start Ta
main block
ta wakup others
main continue

Description: The difference between Park and wait. Wait for the thread to block before it must get the sync lock through synchronized.

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.