多个线程 使用CountDownLatch latch = new CountDownLatch(1); 等待所有的事情都做完 出现报错:
Exception in thread "t1" java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.wait(Native Method)
at java.base/java.lang.Object.wait(Object.java:328)
at Lock_Condition_Thread_02.lambda$main$0(Lock_Condition_Thread_02.java:23)
at java.base/java.lang.Thread.run(Thread.java:834)
A
try {
latch.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
在以下代码中
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Lock_Condition_Thread_02 {
public static void main(String[] args) {
final Object ob = new Object();
char[] arr = "123456789".toCharArray();
char[] arr2 = "ABCDEFGHL".toCharArray();
Lock lock = new ReentrantLock();//可重入锁
Condition condition = lock.newCondition();//队列1
Condition condition2 = lock.newCondition();//队列2
CountDownLatch latch = new CountDownLatch(1);
new Thread(() ->{
try {
latch.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
lock.lock();//获取锁
try {
for (char c : arr) {
System.out.println(c);//执行完事务
condition2.signal();//叫醒第2个队列
condition.await();//到第1个队列等待
}
condition2.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
},"t1").start();
new Thread(() ->{
lock.lock();
try {
for (char c : arr2) {
System.out.println(c);
latch.countDown();
condition.signal();//叫醒第1队列
condition2.await();//第2队列等待
}
condition.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
},"t2").start();
}
}
有能解说一下这是为啥蛮 急