MyException - 我的异常网
当前位置:我的异常网» J2SE » 求教底下这个代码结果为什么是随机的

求教底下这个代码结果为什么是随机的(3)

www.MyException.Cn  网友分享于:2013-12-25  浏览:5次

------解决方案--------------------
LZ经过了多次测试,是你想要的结果,你的程序有两个问题1是不要用if判断线程是否等待,等待最好加this.wait(),先判断是否要等待(满足等待的条件就阻塞后面的语句不执行)2是System.out.println()这句没有同步,要写在同步方法里

Java code
public class Wait {
    public static void main(String[] args) {
        Queue q = new Queue();
        (new Producer(q)).start();
        (new Consumer(q)).start();

    }
}

class Queue {
    int value;// 类比一个篮子(共享变量)
    boolean full = false;// 篮子空的

    public synchronized void input(int i) {
        while (full == true)//满足等待条件线程等待,后面语句不执行
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        value = i;// 篮子空了,value获得一个值
        System.out.println("Pruducer put " + i);
        full = true;// 篮子满了
        notify();
    }

    public synchronized void output() {
        while (full == false)
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.println("Consumer get " + value);
        full = false;// 否则篮子置为空
        notify();// 唤醒其他线程
    }
}

class Producer extends Thread {
    Queue q;

    Producer(Queue q) {
        this.q = q;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            q.input(i);

        }
    }
}

class Consumer extends Thread {
    Queue q;

    Consumer(Queue q) {
        this.q = q;
    }

    public void run() {
        while (true) {
            q.output();
        }

    }
}
//结果
Pruducer put 0
Consumer get 0
Pruducer put 1
Consumer get 1
Pruducer put 2
Consumer get 2
Pruducer put 3
Consumer get 3
Pruducer put 4
Consumer get 4
Pruducer put 5
Consumer get 5
Pruducer put 6
Consumer get 6
Pruducer put 7
Consumer get 7
Pruducer put 8
Consumer get 8
Pruducer put 9
Consumer get 9

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有