wati和notify的应用

作者在 2010-05-23 20:16:29 发布以下内容
public class SyncTest{
    public static void main(String args[]){
        SyncStack stack = new SyncStack();
        Runnable p=new Producer(stack);
        Runnable c = new Consumer(stack);
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);
        t1.start();
        t2.start();
    }
}


class  Producer implements Runnable{
    SyncStack stack;    
    public Producer(SyncStack s){
        stack = s;
    }
    public void run(){
        for(int i=0; i<20; i++){
            char c =(char)(Math.random()*26+'A');
            stack.push(c);
            try{                                    
                Thread.sleep((int)(Math.random()*300));
            }catch(InterruptedException e){
            }
        }
    }
}

class Consumer implements Runnable{
    SyncStack stack;    
    public Consumer(SyncStack s){
        stack = s;
    }
    public void run(){
        for(int i=0;i<20;i++){
            char c = stack.pop();
            try{                                      
                Thread.sleep((int)(Math.random()*500));
            }catch(InterruptedException e){
            }
        }
    }
}
public class SyncStack{  //支持多线程同步操作的堆栈的实现
    private int index = 0;
    private char []data = new char[6];    
    public synchronized void push(char c){
        while(index == data.length){
        try{
                this.wait();
            }catch(InterruptedException e){}
            }
        this.notify();
        data[index] = c;
        index++;
        System.out.println("produced:"+c);
    }
    public synchronized char pop(){
        while(index ==0){
            try{
                this.wait();
            }catch(InterruptedException e){}
                    }
        this.notify();
        index--;
        System.out.println("消费:"+data[index]);
        return data[index];
    }
}

线程 | 阅读 1102 次
文章评论,共0条
游客请输入验证码
浏览275865次