栈的实用实例

作者在 2010-05-23 19:53:03 发布以下内容
class Stack{
    int idx=0;
    char[ ] data = new char[6];
    public void push(char c){
        data[idx] = c;
        System.out.print("压入字符" + c + "->");  //p1
        idx++;
        System.out.println("->压入" + c + "操作完成!");        
    }
    public char pop(){
        idx--;
        return data[idx];
    }
}
public class TestCriticalResource{
    public static void main(String args[]){
        Stack s = new Stack();
        s.push('a');
        s.push('b');
        Runner1 r1 = new Runner1(s);
        Runner2 r2 = new Runner2(s);
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);    
        t1.start();
        t2.start();
    }    
}

class Runner1 implements Runnable{
    private Stack s;
    public Runner1(Stack s){
        this.s = s;
    }
    public void run(){
        for(int i=0;i<15;i++){
            System.out.print(i+ "  ");
        }
        s.push('c');
    }    
}

class Runner2 implements Runnable{
    private Stack s;
    public Runner2(Stack s){
        this.s = s;
    }
    public void run(){
        System.out.print("**弹出" + s.pop() + "**");
    }    
}
线程 | 阅读 1053 次
文章评论,共1条
源本英明C
2010-06-21 16:17
1
<img src="image/face/16.gif" class="face">
游客请输入验证码
浏览290861次