package edu.uestc.avatar.demo;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test3 {
private static MyStack stack = new MyStack();
private static class Clerk {
private String name;
public Clerk() {
this.name = "a" + (int) (Math.random() * 10 + 1);
}
@Override
public String toString() {
return name;
}
}
private static class MyStack {
private static final int CAPCITY = 10;
private LinkedList<Clerk> list = new LinkedList<>();
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
// 进栈
public void push(Clerk clerk) {
lock.lock();
try {
while (list.size() == CAPCITY) {
System.out.println("缓冲区已满,等待notFull");
notFull.await();
}
list.addFirst(clerk);
notEmpty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// 出栈
public Clerk pop() {
Clerk clerk = null;
lock.lock();
try {
while (list.isEmpty()) {
System.out.println("缓冲区没有数据,等待notEmpty");
notEmpty.await();
}
clerk = list.removeFirst();
notFull.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return clerk;
}
public int size() {
return list.size();
}
}
private static class Producer implements Runnable {
@Override
public void run() {
while (true) {
try {
Clerk clerk = new Clerk();
stack.push(clerk);
System.out.println("添加" + clerk + "成功!集合中还有" + stack.size() + "个");
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private static class Consumer implements Runnable {
@Override
public void run() {
while (true) {
try {
Clerk clerk = stack.pop();
System.out.println("删除" + clerk + "成功!集合中还有" + stack.size() + "个");
Thread.sleep((int) (Math.random()) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Producer());
executor.execute(new Consumer());
}
}
//运行不出来后续的个数,一直在0,1之间反复横跳。