限制一次只能有特定数的线程进行工作,添加操作写在同步代码块外面,按理只会少删,为啥会爆java.util.NoSuchElementException,求大佬解析
public class A {
LinkedList<Object> activeT = new LinkedList<>();
int a = 1;
public void done() {
synchronized (activeT) {
while (activeT.size() >= 2) {
try {
activeT.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// activeT.addLast("加入" + Thread.currentThread().getName());
}
try {
Thread.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
activeT.addLast("加入" + Thread.currentThread().getName());
synchronized (activeT) {
System.out.println(activeT.size());
activeT.removeFirst();
activeT.notifyAll();
}
}
public static void main(String[] args) {
A a = new A();
Stream.of("A", "B", "C", "D", "E", "F", "G", "H", "K").map(name -> new Thread(() -> {
a.done();
}, name)).forEach(thread -> thread.start());
}
}