接口中有两个一个是向队列中写 push 方法 一个是从队列中读。
public interface StackInterface
{
public void push(int n);
public int[] pop();
}
上边接口的实现类。
public class SafeStack implements StackInterface {
private int top = 0;
private int[] values = new int[10];
private boolean dataAvailable = false;
public void push(int n) {
synchronized (this) {
while (dataAvailable) // 1
{
try {
wait();
} catch (InterruptedException e) {
// 忽略 //2
}
}
values[top] = n;
System.out.println("压入数字" + n + "步骤 1 完成");
top++;
dataAvailable = true;
notifyAll();
System.out.println("压入数字完成");
}
}
public int[] pop() {
synchronized (this) {
while (!dataAvailable) // 3
{
try {
wait();
} catch (InterruptedException e) {
// 忽略 //4
}
}
System.out.print("弹出");
top--;
int[] test = { values[top], top };
dataAvailable = false;
// 唤醒正在等待压入数据的线程
notifyAll();
return test;
}
}
}
读线程
public class PopThread implements Runnable
{
private StackInterface s;
public PopThread(StackInterface s)
{
this.s = s;
}
public void run()
{
while(true)
{
System.out.println("->"+ s.pop()[0] + "<-");
try {
Thread.sleep(100);
}
catch(InterruptedException e){}
}
}
}
写线程
public class PushThread implements Runnable
{
private StackInterface s;
public PushThread(StackInterface s)
{
this.s = s;
}
public void run()
{
int i = 0;
while(true)
{
java.util.Random r = new java.util.Random();
i = r.nextInt(10);
s.push(i);
try {
Thread.sleep(100);
}
catch(InterruptedException e){}
}
}
} |
|