正常情况
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(),不要弄反了
进微信群和大佬面对面学习交流👇🏻👇🏻👇🏻