你把 notify 换成 notifyAll 就行了,前者是唤醒一个线程,后者唤醒所有线程

解决方案 »

  1.   


    我为了用notify() 在等待前就notify()一次啊,为的是防止死锁,但是这样防止死锁了,却唤不醒对方了,结果有两个线程在死循环里了
      

  2.   

    楼主要学会贴代码public class Demo {
        public static void main(String[] args) {
            if (args.length == 0) {
                System.out.println("no args.");
            }
        }
    }像楼主的代码层级多,又没有排版,没法看。
      

  3.   

    似乎wait()被唤醒时,优先级高一点点,可能跟内部实现有点关系,不是太确定。
      

  4.   

    用flag就可以了,wait和notify有用吗
      

  5.   

    你这个肯定是死循环啊,你的线程里都有while(true),并且你的生产者和消费者写的也不对啊,我给你稍微修改了一下,你可以运行看看结果,我把线程里的while去掉了,就执行一次,如果想执行多次,可以加上package learning;class Resource {
    private String name;
    private int count = 0;
    private boolean flag = false; public synchronized void set(String name) {
    /*while (flag) {
    notify();
    try {
    wait();
    } catch (InterruptedException e) {
    }
    System.out
    .println(Thread.currentThread().getName() + "....循环唤醒..."); }*/

    if(count > 0){
    notifyAll();
    }
    count++;
    this.name = name;
    System.out.println(Thread.currentThread().getName() + "....生产者..."
    + this.name + ":" + count);
    try {
    wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return;
    }
    //flag = true;
    //notify(); } public synchronized void out() {
    /*while (!flag) {
    notify();
    try {
    wait();
    } catch (InterruptedException e) {
    }
    System.out
    .println(Thread.currentThread().getName() + "....循环唤醒..."); }*/

    if(count < 1){
    try {
    wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return;
    }
    }
    count--;
    //this.name = name + count;
    System.out.println(Thread.currentThread().getName() + "....消费者......."
    + this.name + ":" + count);
    //flag = false;
    notifyAll();
    }}class Producer implements Runnable {
    Resource r; Producer(Resource r) {
    this.r = r;
    } public void run() {
    //while (true)
    r.set("烤鸭"); }
    }class Consumer implements Runnable {
    Resource r; Consumer(Resource r) {
    this.r = r;
    } public void run() {
    //while (true)
    r.out();
    }
    }public class ProducerConsumerDemo {
    public static void main(String[] args) {
    Resource r = new Resource(); Producer p = new Producer(r);
    Consumer c = new Consumer(r);
    Thread t1 = new Thread(p,"p1");
    Thread t2 = new Thread(p,"p2");
    Thread t3 = new Thread(c,"c1");
    Thread t4 = new Thread(c,"c2");
    t1.start();
    t2.start();
    t3.start();
    t4.start();
    }
    }