synchronized、ReentrantLock、LockSupport 的使用

synchronized 线程等待唤醒机制

  private static final Object objLock = new Object();

    public static void main(String[] args) {
        new Thread(()->{
            synchronized (objLock){
                System.out.println("线程A come in ...");
                try {
                    System.out.println("线程A等待...");
                    objLock.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程A被唤醒");
            }
        },"A").start();

        new Thread(()->{
            synchronized (objLock){
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                objLock.notify();
            }
        },"B").start();
    }

ReentrantLock

 private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println("线程A等待");
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }, "A").start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            try {
          
                condition.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }, "B").start();
    }

LockSupport

Thread threadA = new Thread(() -> {
            System.out.println("线程A等待。。。");
            LockSupport.park();
            System.out.println("线程A被唤醒");
        }, "A");
        threadA.start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LockSupport.unpark(threadA);
            System.out.println("线程B唤醒线程A");
        }).start();
posted @ 2022-10-09 14:08  紫川先生  阅读(21)  评论(0编辑  收藏  举报