import java.util.*;
class Test{
public void run(){
Queen queen=new Queen();
QueenThread qt=new QueenThread(queen);
new Thread(qt).start();
new Thread(qt).start();
}
public static void main(String[]args){
new Test().run();
}
}
class Queen{
private final Object objects[]=new Object[10];
private int pushIndex=0;
private int popIndex=0;
public synchronized void push(Object object){
if(pushIndex>=objects.length){
System.out.println(Thread.currentThread().getName()+" queen is over,push fail!");
}else
objects[pushIndex++]=object;
}
public synchronized Object pop(){
if(popIndex>=objects.length){
System.out.println(Thread.currentThread().getName()+" queen is empty,pop fail!");
}else{
Object object=objects[popIndex];
objects[popIndex++]=null;
Thread.yield();
return object;
}
return null;
}
}
class QueenThread implements Runnable{
private static int id=0;
private Queen queen;
public QueenThread(Queen queen){
this.queen=queen;
}
public void run(){
String object=null;
for(int i=0;i<10;i++){
queen.push(Thread.currentThread().getName()+" "+id);
id++;
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
object=(String)queen.pop();
if(object!=null)
System.out.println(Thread.currentThread().getName()+" |"+object);
}
}
}