同步Consumer-Producer与Java中的线程

时间:2019-01-08 19:08:42

标签: java multithreading get synchronization producer-consumer

我编写了这段代码来尝试理解Java中线程之间的同步,但是当我运行它时,我得到了一个 java.lang.IllegalMonitorStateException 异常。我的代码的条件是: 1)如果cubbyHole包含其他生产者生产的项目,则生产者不能生产项目。 2)如果方孔是空的,则消费者不能消费物品。 这是代码:

import java.util.*;
public class Esercizio1 {
    public static void main(String[] args) {
        CubbyHole c = new CubbyHole();
        Consumer c1 = new Consumer(c, 1);
        Consumer c2 = new Consumer(c, 2);
        Producer p1 = new Producer(c, 10);
        Producer p2 = new Producer(c, 20);
        p1.start(); p2.start();
        c1.start(); c2.start();
    } 
}
class Producer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Producer(CubbyHole c, int number) {
        cubbyhole = c;
        this.number = number;
    }   

    public void run() {
        while (cubbyhole.getAvailable()) {
            try {
                wait();
            } catch (InterruptedException ex) {}
        }
        for (int i = 1; i < 5; i++) {
            int num = number*i;
            cubbyhole.put(num);
            System.out.println("Producer #" + number + " put: " + num);
        } 
        notifyAll();
        cubbyhole.setAvailable(true);
        System.out.println("Producer #" + number + " ha finito"); }
    }


    class Consumer extends Thread {
        private CubbyHole cubbyhole;
        private int number;
        public Consumer(CubbyHole c, int number) {
            cubbyhole = c;
            this.number = number;
        }   

        public void run() {
            int value = 0;
            while (!cubbyhole.getAvailable()) {
                try {
                    wait();
                } catch (InterruptedException ex) {}
            }
            for (int i = 1; i < 5; i++) {
                value = cubbyhole.get();
                System.out.println("Consumer #" + number + " got: " + value);
            } 
            notifyAll();
            cubbyhole.setAvailable(false);
            System.out.println("Consumer #" + number + " ha finito"); 
        }
    }


    class CubbyHole {
        private int content = -1;
        private boolean available = false;
        public int get() { return content; }
        public void put(int value) { content = value; }
        public boolean getAvailable ()  { return available; }
        public void setAvailable (boolean condition) { available = condition; }
    }

0 个答案:

没有答案