Java:wait()和notify()混淆

时间:2016-03-08 03:04:08

标签: java multithreading wait notify

我正在尝试实现只有一个线程可以访问的条件:让我们说它是一瓶水 - 我只想让一个人(线程)能够拥有它。一切似乎都很顺利,但我无法显示打印 - 在致电wait()之前的那个;

public synchronized void getBotttle  {
    while(myCondition) {
      try {
        System.out.println("Printing that is never done?!");
        wait();
      }
      catch (InterruptedException e) {}
    }

    System.out.println("Printing that works");
    myCondition = true;
    notifyAll(); //or notify(), tried both

    try {
      Thread.sleep(time); // 
    }
    catch (InterruptedException e) {}
    System.out.println("Printing again");
    methodToMakeConditionFalse();
   // notifyAll(); even if I put it here its still the same
}

此方法由线程调用,并且按预期工作 - 只有1个线程具有“瓶子”但打印不存在。 有什么想法吗?

3 个答案:

答案 0 :(得分:0)

有效回答非常简单,getBotttle()方法的签名具有关键字synchronized,这意味着永远不会有两个不同的线程同时访问此代码。因此,while(myCondition) { ... }的整个块无效。

其次,我建议你研究java.util.concurrent.*包。

UPD。似乎值得澄清等待/ notifyAll的常用用法是:

public class WaitNotify {

    public static void main(String[] args) throws InterruptedException {
        new WaitNotify().go();
    }

    private void go() throws InterruptedException {
        ResourceProvider provider = new ResourceProvider();
        Consumer c1 = new Consumer("consumer1", provider);
        Consumer c2 = new Consumer("consumer2", provider);
        Consumer c3 = new Consumer("consumer3", provider);
        Consumer[] consumers = new Consumer[] { c1, c2, c3 };

        for (int i = 0; i < consumers.length; i++) {
            provider.grant(consumers[i]);
        }
    }

    public static class ResourceProvider {
        private Resource resource = new Resource();

        public synchronized void grant(Consumer consumer) throws InterruptedException {
            while (resource == null) {
                wait();
            }
            consumer.useResource(resource);
            resource = null;
        }

        public synchronized void putBack(Resource resource) {
            this.resource = resource;
            notifyAll();
        }
    }

    public static class Resource {
        public void doSomething(String consumer) {
            System.out.println("I'm working! " + consumer);
            try {
                Thread.sleep(3L * 1000L);
            } catch (InterruptedException e) { }
        }
    }

    public static class Consumer implements Runnable {
        private String consumer;
        private Resource resource;
        private ResourceProvider provider;

        public Consumer(String consumer, ResourceProvider provider) {
            this.consumer = consumer;
            this.provider = provider;
        }

        public void useResource(Resource r) {
            this.resource = r;
            new Thread(this).start();
        }

        @Override
        public void run() {
            resource.doSomething(consumer);
            provider.putBack(resource);
        }
    }
}

答案 1 :(得分:0)

你没有一个完整的例子,这很难说出你做错了什么;我的猜测是你的状况标志没有正确设置。这是一个有效的完整示例,它确保一次只有一个线程可以访问资源。

public class StuffExample {

    public static void main(String[] args) throws Exception {

        Worker worker = new Worker(new StuffHolder());
        Thread t1 = new Thread(worker); 
        Thread t2 = new Thread(worker); 

        t1.start();
        t2.start();

        Thread.sleep(10000L);
        t1.interrupt();
        t2.interrupt();
    }
}

class Worker implements Runnable {
    private StuffHolder holder;

    public Worker(StuffHolder holder) {
        this.holder = holder;
    }

    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                holder.useStuff();
                Thread.sleep(1000L);
            }
        }
        catch (InterruptedException e) {
        }
    }
}

class StuffHolder {

    private boolean inUse = false;
    private int count = 0;
    public synchronized void useStuff() throws InterruptedException {
        while (inUse) {
            wait();
        }
        inUse = true;
        System.out.println("doing whatever with stuff now, count=" 
            + count + ", thread=" + Thread.currentThread().getName());
        count += 1;
        inUse = false;
        notifyAll();
    }   
}

输出是:

doing whatever with stuff now, count=0, threadid=Thread-0
doing whatever with stuff now, count=1, threadid=Thread-1
doing whatever with stuff now, count=2, threadid=Thread-0
doing whatever with stuff now, count=3, threadid=Thread-1
doing whatever with stuff now, count=4, threadid=Thread-0
doing whatever with stuff now, count=5, threadid=Thread-1
doing whatever with stuff now, count=6, threadid=Thread-0
doing whatever with stuff now, count=7, threadid=Thread-1
doing whatever with stuff now, count=8, threadid=Thread-0
doing whatever with stuff now, count=9, threadid=Thread-1
doing whatever with stuff now, count=10, threadid=Thread-0
doing whatever with stuff now, count=11, threadid=Thread-1
doing whatever with stuff now, count=12, threadid=Thread-0
doing whatever with stuff now, count=13, threadid=Thread-1
doing whatever with stuff now, count=14, threadid=Thread-0
doing whatever with stuff now, count=15, threadid=Thread-1
doing whatever with stuff now, count=16, threadid=Thread-1
doing whatever with stuff now, count=17, threadid=Thread-0
doing whatever with stuff now, count=18, threadid=Thread-1
doing whatever with stuff now, count=19, threadid=Thread-0

请参阅Oracle's tutorial on guarded blocks

答案 2 :(得分:0)

非常感谢你们两个。我会尝试将所有内容写清楚,以便其他人坚持使用类似的东西可以解决它。

我拥有的是2个主题(比方说2个人)。他们都要从1瓶中喝水,所以当瓶子在使用时,第二个人必须等待。我的代码大致如下:

class Bottle{
 private boolean inUse=false;

 public synchronized void getBotttle(String name, int time)  {
    while(inUse) {
      try {
        System.out.println("The bottle is in use. You have to wait");
        wait();
      }
      catch (InterruptedException e) {}
    }

    System.out.println("Person "+name+" is using the bottle");
    inUse = true;
    notify(); //or notifyAll(), tried both

    try {
      Thread.sleep(time); // sleep the Thread with the person that is drinking at the moment for some time in order for him to finish
    }
    catch (InterruptedException e) {}
    System.out.println("The bottle is now free");
    inUse=false;
   // notify(); even if I put it here its still the same
 }
}

我刚开始在java中使用Threads,所以我不确定notify()应该去哪里。更有甚者,我不明白notify()只有在执行了具有关键字synchronized的所有块之后才释放锁。在我的情况下,这不是我想要的,并且当释放锁时发生,while方法的条件将为false并且不会执行打印。程序正在等待并按预期进行的事实使我很难发现这一点。

这就是我想要的和我的工作:

class Bottle{
 private boolean inUse=false;

 public void getBotttle(String name, int time)  {
    while(inUse) {
      try {
        System.out.println("The bottle is in use. You have to wait.");
        synchronized(this){
         wait();
        }
      }
      catch (InterruptedException e) {}
    }

    System.out.println("Person "+name+" is using the bottle");
    inUse = true;

    try {
      Thread.sleep(time); // sleep the Thread with the person that is drinking at the moment for some time in order for him to finish
    }
    catch (InterruptedException e) {}
    System.out.println("The bottle is free now.");
    inUse=false;
    synchronized(this){
     notifyAll();
    }
 }
}

希望最后编辑: 这应该可以防止2个线程跳过while循环,并且应该是我正在寻找的解决方案

class Bottle{
 private boolean inUse=false;

 public synchronized void getBotttle(String name, int time)  {
    while(inUse) {
      try {
        System.out.println("The bottle is in use. You have to wait.");
        wait();
      }
      catch (InterruptedException e) {}
    }

    System.out.println("Person "+name+" is using the bottle");
    inUse = true;
 }

 public synchronized void sleeping(String name, int time)
    try {
      Thread.sleep(time); // sleep the Thread with the person that is drinking at the moment for some time in order for him to finish
    }
    catch (InterruptedException e) {}
    notifyAll();
    System.out.println("The bottle is free now.");
    inUse=false;
 }
}

编辑: 猜不是,打印那个正在使用的瓶子并没有被执行...