Java concurrency tool LockSupport

Source: Internet
Author: User

Java concurrency tool LockSupport
LockSupport

In the J. U. C framework, there is a class called LockSupport, which can accurately block and wake up specific threads and serve as the primitives of other synchronization classes.
LockSupport includes a park (Object blocker) and an unpark (Object blocker) method for blocking and wakeup, respectively.

For example, the following code contains a thread thread1 and a main thread. In thread1, the park method is called, The unpark method is called in the main thread, and the thread1 status is printed:

import java.util.concurrent.locks.LockSupport;public class Main{    public static void main(String[] args) throws InterruptedException {    Thread thread1 = new Thread(new Runnable() {        @Override        public void run() {        System.out.println(thread 1 start);        LockSupport.park(Thread.currentThread());        try {            Thread.sleep(4000);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(thread 1 end);        }    });    thread1.start();    System.out.println(main thread start,thread1 +thread1.getState());    Thread.sleep(2000);    System.out.println(main thread running,thread1 +thread1.getState());    LockSupport.unpark(thread1);    Thread.sleep(6000);    System.out.println(main thread end,thread1 +thread1.getState());    }}

Execution result:

Thread 1 start
Main thread start, thread1 RUNNABLE
Main thread running, thread1 WAITING
Thread 1 end
Main thread end, thread1 TERMINATED

As you can see, thread1 becomes WAITTING after the park, and then wake up after the unpark and continue until the execution ends.

 

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.