62,615
社区成员
发帖
与我相关
我的任务
分享
public class Demo {
@Test
public void test() throws InterruptedException {
new Thread(new Customer()).start();
new Thread(new Producer()).start();
new Thread(new Customer()).start();
new Thread(new Producer()).start();
while (Thread.activeCount() > 2){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Store{
private volatile static Store instance;
private AtomicInteger index;
private ArrayBlockingQueue<Integer> queue;
private Store(){
index = new AtomicInteger();
queue = new ArrayBlockingQueue<>(3);
}
public static Store getInstance(){
if (instance == null){
synchronized (Store.class){
if (instance == null){
instance = new Store();
}
}
}
return instance;
}
public void put(){
int i = index.incrementAndGet();
try {
queue.put(i);
System.out.println("生产:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void take(){
Integer take;
try {
take = queue.take();
System.out.println("\t 消费" + take);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Customer implements Runnable{
private Store store;
public Customer(){
store = Store.getInstance();
}
@Override
public void run() {
for (int i = 0; i < 10; i++){
store.take();
}
}
}
class Producer implements Runnable{
private Store store;
public Producer(){
store = Store.getInstance();
}
@Override
public void run() {
for (int i = 0; i < 10; i++){
store.put();
}
}
}