JUC-await和signal

正常情况

    public static void main(String[] args) {
        new Thread(()->{
            lock1.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + " 被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
            }
        }, "t1").start();
        new Thread(()-> {
            lock1.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + " 发出唤醒通知");
            } finally {
                lock1.unlock();
            }
        }, "t2").start();
    }

t1 come in
t2 发出唤醒通知
t1 被唤醒 

异常情况:先signal,导致唤醒无法唤醒

    public static void main(String[] args) {
        new Thread(()->{
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            lock1.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + " 被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
            }
        }, "t1").start();
        new Thread(()-> {
            lock1.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + " 发出唤醒通知");
            } finally {
                lock1.unlock();
            }
        }, "t2").start();
    }

 JUC-await和signal

异常情况:await和signal没有在lock代码块中会报异常

    static Lock lock1 = new ReentrantLock();
    static Condition condition = lock1.newCondition();
    public static void main(String[] args) {
        new Thread(()->{
//            lock1.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + " 被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
//                lock1.unlock();
            }
        }, "t1").start();
        new Thread(()-> {
//            lock1.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + " 发出唤醒通知");
            } finally {
//                lock1.unlock();
            }
        }, "t2").start();
    }

JUC-await和signal

总结:

Condtion中的线程等待和唤醒方法之前,需要先获取锁;

一定要先await(),后signal(),不要弄反了

上一篇:Async Await 多线程等待 应用


下一篇:2021/12/6