血泪教训呀同学们,判空判溢出那里,一定一定要用while呀!!!
public class Pro {
public static Queue<Integer> que = new LinkedList<>();
class producer implements Runnable{
@Override
public void run() {
while(true){
synchronized (que){
while(que.size()==10){
System.out.println("满了");
que.notify();
try {
que.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
que.offer(1);
System.out.println("生产"+que.size());
que.notify();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class consumer implements Runnable{
@Override
public void run() {
while(true){
synchronized (que){
while(que.size()==0){
que.notify();
System.out.println("空了");
try{
que.wait();
} catch (Exception e){
e.printStackTrace();
}
}
que.poll();
System.out.println("消费"+que.size());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Pro pro = new Pro();
producer produc = pro.new producer();
consumer consumer = pro.new consumer();
for(int i = 0; i < 10; i++){
new Thread(produc).start();
new Thread(consumer).start();
}
}
}