线程:如何在线程消费者中检查数据接收检查

时间:2013-05-23 13:02:56

标签: java multithreading

我有这个生产者消费者样本计划如下所示

如何在我的Consumer Thread类中放置一个Condition,这样如果我没有从生产者那里重新获取数据1分钟,我需要记录那个??

这是我的制片人消费者计划

public class ProducerConsumerTest {
    public static void main(String[] args) {
        CubbyHole c = new CubbyHole();
        Producer p1 = new Producer(c, 1);
        Consumer c1 = new Consumer(c, 1);
        p1.start();
        c1.start();
    }
}

class CubbyHole {
    private int contents;
    private boolean available = false;

    public synchronized int get() {
        while (available == false) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        available = false;
        notifyAll();
        return contents;
    }

    public synchronized void put(int value) {
        while (available == true) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        contents = value;
        available = true;
        notifyAll();
    }
}



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(true)
        {
        for (int i = 0; i < 100000; i++) {
            cubbyhole.put(i);
            System.out.println("Producer #" + this.number + " put: " + i);
            try {
                sleep((int) (Math.random() * 2000));
            } catch (Exception e) {
            }
        }
        }
    }
}


class Consumer extends Thread {
    private CubbyHole cubbyhole;
    private int number;

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

    public void run() {
        while(true)
        {
        int value = 0;
        for (int i = 0; i < 100000; i++) {
            value = cubbyhole.get();
            System.out.println("Consumer #" + this.number + " got: " + value);
        }
        }
    }
}

有人可以帮忙吗

2 个答案:

答案 0 :(得分:2)

您可以使用Object#wait(long timeout)并在get()方法内登录:

try {
    wait(60 * 1000);
    if (available == false) {
        //log
    }
} catch (InterruptedException e) {
}

答案 1 :(得分:1)

Consumer run方法:

long before;
for (int i = 0; i < 100000; i++) {
        before = System.currentTimeMilis();
        value = cubbyhole.get();
        if (System.currentTimeMilis() - before > 1000 * 60) {
            System.out.println("Consumer waited for more than one minute");
        }
        System.out.println("Consumer #" + this.number + " got: " + value);
}
中使用System.currentTimeMilis()