Stack.java
import java.util.concurrent.locks.Conditionimport java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
public class Stack {
private int[] data
private int index
private Lock lock
private Condition moreSpace
private Condition moreEelment
public Stack(int size){
this.data = new int[size]
this.index = 0
this.lock = new ReentrantLock()
this.moreSpace = lock.newCondition()
this.moreEelment = lock.newCondition()
}
public void push(int value){
lock.lock()
try {
while(index == data.length){
moreSpace.await()
}
data[index++] = value
moreEelment.signalAll()
} catch (InterruptedException e) {
e.printStackTrace()
} finally {
lock.unlock()
}
}
public int popup(){
lock.lock()
int value = 0
try {
while(index == 0){
moreEelment.await()
}
value = data[--index]
moreSpace.signalAll()
} catch (InterruptedException e) {
e.printStackTrace()
} finally {
lock.unlock()
}
return value
}
}
写入线程 WriteStack.java
import java.util.Randompublic class WriteStack implements Runnable {
private Stack stack
public WriteStack(Stack stack){
this.stack = stack
}
@Override
public void run() {
Random r = new Random(System.currentTimeMillis())
for(int i = 0i < 10 i++){
int value = r.nextInt(500)
stack.push(value)
System.out.printf("Write: push %d in stack\n",value)
try {
Thread.sleep(r.nextInt(500))
} catch (InterruptedException e) {
e.printStackTrace()
}
}
}
}
读取线程 ReadStack.java
import java.util.Randompublic class ReadStack implements Runnable {
private Stack stack
public ReadStack(Stack stack){
this.stack = stack
}
@Override
public void run() {
Random r = new Random(System.currentTimeMillis())
for(int i = 0i < 10 i++){
int value = stack.popup()
System.out.printf("Read: popup an element %d\n",value)
try {
Thread.sleep(r.nextInt(500))
} catch (InterruptedException e) {
e.printStackTrace()
}
}
}
}
主测试线程 StackExample.java
public class StackExample {public static void main(String[] args) throws InterruptedException {
Stack stack = new Stack(5)
WriteStack writeStack = new WriteStack(stack)
ReadStack readStack = new ReadStack(stack)
Thread writeThread = new Thread(writeStack)
Thread readThread = new Thread(readStack)
writeThread.start()
readThread.start()
}
}
使用java.util包中的Stack类创建一个栈对象public Object push(Object data)输入数据,实现压栈
public Object pop()输出数据,实现d栈
public boolean empty()判空
public Object peek()查看栈顶元素
可以去查查API嘛
我也是学java的,大家一起进步。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)