开发者

Use guarded blocks for one Producer - many Consumer application

Following this example in the Java(tm) tutorials, I have implemented this basic one producer - one consumer application in Delphi 2009 (which introduced object locks).

Now I would like to extend it so that more than one consumer thread takes messages from the Drop instance. Compared with the Java tutorial example, the only code change would be in the main method:

public class ProducerConsumerExample {
    public static void main(String[] args) {

        Drop drop = new Drop();

        (new Thread(new Producer(drop))).start();

        (new Thread(new Consumer(drop))).start();
        (new Thread(new Consumer(drop))).start(); // <--- added
        (new Thread(new Consumer(drop))).start(); // <--- added 
开发者_JAVA百科    }
}

So the Drop class would still have one message object of type String, and all running consumers will compete to get access to the lock, and process the message data.

Would this code change introduce risks, or is it safe to use?


According to code from linked sample, you won't be able to stop more than one consumer. So, you either need to add stop() method to consumer class, or post DONE as many times as many consumers are there.

Except this, there are no risks.

But if you wish to increase throughput of your producer-consumer, you may consider using class that can hold more than one value at the time -- some kind of queue, for example BlockingQueue from JDK. This way your producers and consumers won't be blocked so often as in this code sample.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜