Surprise concurrent programming JUC series - Locksupport and Condition

Surprise concurrent programming JUC series demonstration code address:
https://github.com/mtcarpenter/JavaTutorial

Locksupport

LockSupport in rt.jar package in JDK is a tool class. When a thread needs to be blocked or awakened, you can use LockSupport tool class to complete the corresponding work. LockSupport defines a set of public static methods, which provide the most basic thread blocking and wake-up functions, and LockSupport has also become the basic tool for building synchronization components. LockSupport defines a set of methods starting with park to block the current thread, and an unpark(Thread thread) method to wake up a blocked thread. The following describes several main functions in LockSupport.

  • void park(): blocks the current thread. If the unpark(Thread thread) method is called or the current thread is interrupted, it can be returned from the park() method.
  • void parkNanos(long nanos): blocks the current thread for up to nanoseconds. The return condition adds a timeout return based on park().
  • void parkUntil(long deadline): block the current thread and know the deadline time (the number of milliseconds from 1970 to deadline time).
  • void unpark(Thread thread): wakes up a thread in a blocked state.
  • void park(Object blocker): blocks the current thread. Blocker is used to identify the object that the current thread is waiting for.
  • parkNanos(Object blocker, long nanos): it increases the timeout time compared with void park(Object blocker).
  • parkUntil(Object blocker, long deadline): blocks the current object one more than void parkUntil(long deadline).

Locksupport case

public class LockExample4 {


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

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

}

Operation results:

t1 Start blocking
t2 start
t2 The block has been released
t1 The block has been released

Condition

Any Java object has a set of monitor methods (defined on java.lang.Object), mainly including wait(), wait(long timeout), notify() and notifyAll() methods. These methods cooperate with the synchronized synchronization keyword to realize the wait / notification mode.
The Condition interface also provides a monitor method similar to Object. In combination with Lock, the wait / notify mode can be realized, but there are still differences in usage and functional characteristics between the two.

Condition method description

void await() throws InterruptedException: the current thread enters the waiting state until it is notified or interrupted. The current thread will enter the running state and return from the await() method. include:

  • Other threads call the signal() or signalAll() method of the Condition, and the current thread is selected to wake up

    • Another thread (calling the Interrupt() method) interrupts the current thread
    • If the current waiting thread returns from the await() method, it indicates that the thread has obtained the lock corresponding to the Condition object
  • Void awaituninterruptible(): the current thread is notified of entering the waiting state. From the return name of the method, it can be seen that the method is not sensitive to interrupt
  • long awaitNanos(long nanosTimeout): the current thread enters the waiting state until it is notified, interrupted or timed out. The return value indicates the remaining time. If you wake up nanosecond before nanosTimeout, the return value is (nanosTimeout - actual time). If you return 0 or a negative number, you can assume that it has timed out
  • Boolean await until (date deadline): the current thread enters the waiting state until it is notified, interrupted or at a certain time. If you are notified before the specified time, the method returns true. Otherwise, it means that the specified time is reached, and the method returns false.
  • void signal(): wakes up a thread waiting on Condition. The thread must obtain the Condition related lock before returning from the waiting method
  • void signalAll(): wake up all the threads waiting on Condition. The threads that can return from the waiting method must obtain the lock related to Condition

Condition case

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() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "Start blocking");
                    condition.await();
                    System.out.println(Thread.currentThread().getName() + "The block has been released");
                } catch (InterruptedException e) {
                } finally {
                    lock.unlock();
                }
            }
        }, "t1");
        t1.start();
        TimeUnit.SECONDS.sleep(3);
        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "Start blocking");
                    condition.signalAll();
                    System.out.println(Thread.currentThread().getName() + "The block has been released");
                } finally {
                    lock.unlock();
                }
            }
        }, "t2").start();
    }

}

Operation results:

t1 Start blocking
t2 Start blocking
t2 The block has been released
t1 The block has been released

Welcome to pay attention to the official account mountain carpenter. I'm xiaochunge. I'm engaged in Java back-end development. I'm a bit of a front-end developer and meet friends by continuously outputting a series of technical articles. If this article can help you, you are welcome to pay attention, like and share support_ See you next time_

Tags: Java Back-end

Posted by thinsoldier on Wed, 11 May 2022 11:56:19 +0300