Skip to content

Commit

Permalink
concurrent test
Browse files Browse the repository at this point in the history
  • Loading branch information
javahongxi committed Aug 13, 2019
1 parent dc4da67 commit fe9af85
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 129 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.hongxi.java.util.concurrent;

/**
* @author shenhongxi 2019/8/13
*/
public class BlockingStack<E> {
private static final int DEFAULT_CAPACITY = 10;

Object[] items;
int size;

BlockingStack() {
items = new Object[DEFAULT_CAPACITY];
}

BlockingStack(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
items = new Object[capacity];
}

public synchronized void push(E item) {
while (size == items.length) {
try {
this.wait();
} catch (InterruptedException e) {}
}
this.notifyAll();
items[size++] = item;
}

public synchronized E pop() {
while (size == 0) {
try {
this.wait();
} catch (InterruptedException e) {}
}
this.notifyAll();
return (E) items[--size];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.hongxi.java.util.concurrent;

/**
* @author shenhongxi 2019/8/13
*/
public class BlockingStackTest {

public static void main(String[] args) {
BlockingStack<String> stack = new BlockingStack<>(10);

new Thread(new Producer(stack, "p1")).start();
new Thread(new Consumer(stack, "c1")).start();
new Thread(new Producer(stack, "p2")).start();
new Thread(new Consumer(stack, "c2")).start();
}

static class Consumer implements Runnable {
private BlockingStack stack;
private String name;

public Consumer(BlockingStack stack, String name) {
this.stack = stack;
this.name = name;
}

@Override
public void run() {
for (int i = 0; i < 60; i++) {
Object o = stack.pop();
System.err.println(name + " consume: " + o);
try {
Thread.sleep((long) (Math.random() * 400));
} catch (InterruptedException e) {}
}
}
}

static class Producer implements Runnable {
private BlockingStack stack;
private String name;

public Producer(BlockingStack stack, String name) {
this.stack = stack;
this.name = name;
}

@Override
public void run() {
for (int i = 0; i < 60; i++) {
String data = name + "-" + i;
stack.push(data);
System.out.println(name + " produce: " + data);
try {
Thread.sleep((long) (Math.random() * 100));
} catch (InterruptedException e) {}
}
}
}
}

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

0 comments on commit fe9af85

Please sign in to comment.