其他分享
首页 > 其他分享> > JUC-await和signal

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();
    }

 

异常情况: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();
    }

总结:

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

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

标签:JUC,Thread,currentThread,signal,await,System,lock1,getName,out
来源: https://blog.csdn.net/qq_39940205/article/details/120555115