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();
    }
}

生产者与消费者问题
public class TestProducerConsumer{ public static void main(String[] agrs){ SyncStack ss = new SyncStack(); Producer p = new Producer; ConSumer c = new ConSumer; new Thread.start(); new Thread.start(); }}class Woto{ int id; public Woto{ this.id = id; } public String toString(){ return “Woto:” + id; }}class SyncStack{ int index = 0; Woto[] w = new Woto[8]; public synchronized void push{ while(index == w.length){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); w[index] = wt; index++; } public synchronized Woto pop(){ while(index == 0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index–; return w[index]; }}class Producer implements Runnable{ SyncStack ss = null; public Producer(SyncStack ss){ this.ss = ss; } public void run() { for(int i = 0;i<10;i++){ Woto wt = new Woto; ss.push; System.out.println("生产了="+wt); try { Thread.sleep (Math.random; } catch (InterruptedException e) { e.printStackTrace(); } } }}class ConSumer implements Runnable{ SyncStack ss = null; public ConSumer(SyncStack ss){ this.ss = ss; } public void run() { for(int i = 0;i<10;i++){ Woto wt =ss.pop(); System.out.println("消费了="+wt); try { Thread.sleep (Math.random); } catch (InterruptedException e) { e.printStackTrace(); } } }}

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){
澳门新葡亰游戏网址,            }
        }
    }
}

为什么会先出现消费者呢 ?求大神解答

网站地图xml地图