简体   繁体   English

线程之间的通信被阻止

[英]Blocked communication between Threads

As my title said I have to implement a program where threads communicate with each other by sending message (serializable object). 正如我的标题所说,我必须实现一个程序,其中线程通过发送消息(可序列化对象)相互通信。 The fact is that I want threads to be blocked if they don't have a message waiting. 事实是,如果没有消息等待,我希望阻止线程。 I have already checked on Google and I have found 2 solutions : the first one use ObjectStream with PipedStream and the second one use BlockingQueue. 我已经在Google上查了一下,我找到了2个解决方案:第一个使用ObjectStream和PipedStream,第二个使用BlockingQueue。 My problem is that the 2 solutions seem not to be the best one because PipedStream have lots of bug (I have so much while doing tests) and BlockingQueue do not blocked the thread when the queue is empty. 我的问题是2个解决方案似乎不是最好的解决方案,因为PipedStream有很多错误(我在测试时有很多错误)并且当队列为空时BlockingQueue不会阻塞线程。

So has everyone a solution for my problem ? 那么每个人都能解决我的问题吗?

Thanks in advance ;) 提前致谢 ;)

This is basically a producer/consumer, where a thread can be either or both a producer and a consumer. 这基本上是生产者/消费者,其中一个线程可以是生产者和消费者之一或两者。 I believe that BlockingQueue offers you the solution you need ( http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html ). 我相信BlockingQueue为您提供所需的解决方案( http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html )。 Particularly, look at the put() and take() methods. 特别是,看看put()take()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM