Surprise concurrent programming JUC series demo code address: github.com/mtcarpenter…

Locksupport

LockSupport is a utility class that can be used to block or wake up a thread. LockSupport defines a set of common static methods that provide the most basic thread-blocking and wake up functionality, and LockSupport becomes a basic tool for building synchronized components. LockSupport defines a set of methods starting with park to block the current Thread, and unpark(Thread Thread) to wake up a blocked Thread. Here are some of the main functions in LockSupport.

  • void park(): blocks the current thread if calledunpark(Thread thread)Method or the current thread is interrupted before thepark()Method returns.
  • void parkNanos(long nanos): blocks the current thread up to a maximumnanosNanosecond, the return condition ispark()Based on the added timeout return.
  • void parkUntil(long deadline): blocks the current thread, knowing the deadline time (the number of milliseconds from 1970 to the deadline time).
  • void unpark(Thread thread): Wakes up the blocking thread.
  • void park(Object blocker)Blocker: Blocks the current thread. The blocker identifies the object on which the current thread is waiting.
  • parkNanos(Object blocker, long nanos): better thanvoid park(Object blocker)Add a timeout.
  • parkUntil(Object blocker, long deadline): better thanvoid parkUntil(long deadline)One more block the current object.

Locksupport case start

public class LockExample4 {


    public static void main(String[] args) throws Exception {

 Thread t1 = new Thread(new Runnable() {  @Override  public void run(a) {  System.out.println(Thread.currentThread().getName() + "Start blocking");  LockSupport.park();  System.out.println(Thread.currentThread().getName() + "The blockage has been released.");  }  }, "t1");  t1.start();  TimeUnit.SECONDS.sleep(3);  new Thread(new Runnable() {  @Override  public void run(a) {  System.out.println(Thread.currentThread().getName() + "Start");  LockSupport.unpark(t1);  System.out.println(Thread.currentThread().getName() +"The blockage has been released.");  }  }, "t2").start();  }  } Copy the code

Running results:

T1 starts blockingT2 beganThe T2 block has been releasedThe T1 block has been releasedCopy the code

Condition

Any Java Object has a set of monitor methods (defined on java.lang.object), including wait(), wait(long timeout), notify(), and notifyAll(). These methods work with the synchronized synchronization keyword to implement wait/notification mode. The Condition interface also provides object-like monitor methods that work with Lock to implement wait/notification patterns, but the two differ in usage and functionality.

Condition method description

Void await() throws InterruptedException: The condition in which the current thread enters the wait state until it is notified (signal) or interrupts and the current thread enters the run state and returns from the await() method. Include:

  • Other threads call thisConditionsignal()signalAll()Method while the current thread is selected to wake up
    • Other threads (callInterrupt()Method to interrupt the current thread
    • If the current waiting thread fromawait()Method returns, indicating that the thread has already fetchedConditionThe lock corresponding to the object
  • void awaitUninterruptibly(): The current thread is notified when it enters the wait state. As you can see from the return name of the method, this method is not interrupt-sensitive
  • long awaitNanos(long nanosTimeout): The current thread enters the wait state until notified, interrupted, or timed out. The return value represents the time remaining, which is (nanosTimeout- actual time) if awakened before nanosTimeout is nanosTimeout. If 0 or a negative number is returned, the timeout is considered
  • boolean awaitUntil(Date deadline): The current thread enters the wait state until it is notified, interrupted, or reached a certain time. This method returns true if it is not notified by the specified time, false otherwise.
  • void signal(): Wake up a waiting inConditionThe thread must obtain and from the wait method before returningConditionRelated to the lock
  • void signalAll(): Wake up all waiting inConditionThreads that can return from the wait method must obtain andConditionRelated to the lock

Condition case learning

public class LockExample5 {


    public static void main(String[] args) throws Exception {
        Lock lock = new ReentrantLock();
 Condition condition = lock.newCondition();   Thread t1 = new Thread(new Runnable() {  @Override  public void run(a) {  lock.lock();  try {  System.out.println(Thread.currentThread().getName() + "Start blocking");  condition.await();  System.out.println(Thread.currentThread().getName() + "The blockage has been released.");  } catch (InterruptedException e) {  } finally {  lock.unlock();  }  }  }, "t1");  t1.start();  TimeUnit.SECONDS.sleep(3);  new Thread(new Runnable() {  @Override  public void run(a) {  lock.lock();  try {  System.out.println(Thread.currentThread().getName() + "Start blocking");  condition.signalAll();  System.out.println(Thread.currentThread().getName() + "The blockage has been released.");  } finally {  lock.unlock();  }  }  }, "t2").start();  }  } Copy the code

Running results:

T1 starts blockingT2 starts blockingThe T2 block has been releasedThe T1 block has been released
Copy the code

Welcome to pay attention to the public number Shanma carpenter, I am Xiao Chun brother, engaged in Java back-end development, will be a little front-end, through the continuous output of a series of technical articles to literary friends, if this article can help you, welcome everyone to pay attention to, like, share support, we see you next period!