package alice;
import java.util.concurrent.atomic.AtomicInteger;
public class LockFreeQueue {
AtomicInteger tail=new AtomicInteger(0);
AtomicInteger head=new AtomicInteger(0);
Object[] queue;
int len;
public LockFreeQueue(int size) {
// TODO Auto-generated constructor stub
queue=new Object[size+1];
len=size+1;
}
public boolean push(Object obj) {
int tail_curent=tail.get()+1;
tail_curent=tail_curent%len;
if(tail_curent==head.get()) {
return false;
}
queue[tail.get()]=obj;
tail.set(tail_curent);
return true;
}
public Object pop() {
int head_curent=head.get();
if(head_curent==tail.get()) {
return null;
}
Object obj=queue[head.get()];
head_curent=(head_curent+1)%len;
head.set(head_curent);
return obj;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LockFreeQueue queue=new LockFreeQueue(100000);
Thread pro=new Thread(new producer(queue),"producer");
Thread con=new Thread(new consumer(queue),"consumer");
long start=System.currentTimeMillis(); //获取开始时间
pro.start();
con.start();
try {
pro.join();
con.join();
long end=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(end-start)+"ms");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static class producer implements Runnable{
LockFreeQueue queue;
public producer(LockFreeQueue queue) {
// TODO Auto-generated constructor stub
this.queue=queue;
}
public void run() {
// TODO Auto-generated method stub
int t=1;
while(t<10000) {
Object obj=new Object();
while(!queue.push(obj)) {
System.out.println("生产者等待生产"+t+"商品");
}
System.out.println("生产者生产"+t+"商品");
t++;
}
}
}
public static class consumer implements Runnable{
LockFreeQueue queue;
public consumer(LockFreeQueue queue) {
// TODO Auto-generated constructor stub
this.queue=queue;
}
public void run() {
// TODO Auto-generated method stub
int t=1;
while(t<10000) {
Object obj=new Object();
while(queue.pop()==null) {
System.out.println("消费者等待消费"+t+"商品");
}
System.out.println("消费者消费"+t+"商品");
t++;
}
}
}
}