public interface StackInterface {public void push(int n);public int[] pop();
}
// 上邊接口的實(shí)現(xiàn)類(lèi)。
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) {try {wait();} catch (InterruptedException e) {}}values[top] = n;System.out.println("壓入數(shù)字" + n + "步驟1完成");top++;dataAvailable = true;notifyAll();System.out.println("壓入數(shù)字完成");}}public int[] pop() {synchronized (this) {while (!dataAvailable) {try {wait();} catch (InterruptedException e) {}}System.out.println("彈出");top--;int[] test = {values[top],top};dataAvailable = false;//喚醒正在等待壓入數(shù)據(jù)的線程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){}}}
}
//寫(xiě)線程 ?
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){}}}
}