关于同步和线程的练习

Exercise on synchronization and threads

我正在做一个简单的练习来理解线程和同步的概念。但是不知道代码对不对

public class PopcornMachine {

    // shared resource
    private boolean isBinFull = false; 

    // producer method
    public synchronized void placePopcorn () throws InterruptedException { 
        while (true) {
            while (!isBinFull) wait ();
            isBinFull = true;
            System.out.println(isBinFull);
            notify ();
            Thread.sleep(1000);
        }
    }

    // consumer code
    public synchronized void takePopcorn () throws InterruptedException {
        while (true) {
            while (isBinFull) wait ();
            isBinFull = false;
            System.out.println(isBinFull);
            notify ();
            Thread.sleep(1000);
        }
    }
}

public class PopcornDemo {
    public static void main (String[] args) throws InterruptedException{
        final PopcornMachine machine = new PopcornMachine();

        Thread produce = new Thread (new Runnable() { 
            public void run() { 
                try { 
                    machine.placePopcorn (); 
                } catch(InterruptedException e) {}                 
            }
        }); 

        Thread consume = new Thread (new Runnable() { 
            public void run() { 
                try { 
                    machine.takePopcorn (); 
                } catch(InterruptedException e) {} 
            }
        }); 

        produce.start();
        consume.start();

        produce.join();
        consume.join();
    }
}

我的答案是: 错误的 错误的 错误的 错误的 错误的 假

但感觉不对。代码中间不应该有一个真正的价值吗?

更改 while 条件,如下所示,然后查看评论。使用您当前的代码生产者永远不会执行。

为什么?因为 isBinFull 最初设置为 false 并且在消费者中也设置为 false

在您的生产者代码中

while (!isBinFull) wait (); 

永远不会变成 false 并在 while 循环中继续等待。

更改如下代码

 public synchronized void placePopcorn () throws InterruptedException { 
        while (true) {
            while (isBinFull) wait(); //Look here, waiting since bin is full
            isBinFull = true;
            System.out.println(Thread.currentThread().getName() + ":"+isBinFull);
            notifyAll ();
            Thread.sleep(500);
        }
    }

    // consumer code
    public synchronized void takePopcorn () throws InterruptedException {
        while (true) {
            while (!isBinFull) wait(); ////Look here, waiting since bin is not full
            isBinFull = false;
            System.out.println(Thread.currentThread().getName() + ":"+isBinFull);
            notifyAll ();
            Thread.sleep(500);
        }
    }

在方法级别本身使用 synchronised 确保一次只有一个线程执行。
synchronised 关键字在它被调用的对象上采用 lockmachine 在你的情况下,因此代码不是生产者 - 消费者问题的正确实现。