Java线程通信

发布于 2024-10-31 05:23:19 字数 294 浏览 3 评论 0原文

我正在做一个项目,其中我必须使线程进行通信。

例如,

我有两个线程数组,c[100]e[10]。 (客户和员工)

一旦客户说 c[3] 获取信号量,让它与其中一名员工说员工 e[5] 通话,我如何关联将线程 c[3] 表示的 Customer 对象传递给 Employee 对象 e[5],并让他们来回传递信息?

I am doing a project in which I must make threads communicate.

For instance

I have two thread arrays, c[100] and e[10]. (customers and employees)

Once a customer say c[3] acquires a semaphore to let it speak with one of the employees say employee e[5], how do I associate the Customer object represented by the thread c[3] to the Employee object e[5], and let them pass info back and forth?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌路黄昏 2024-11-07 05:23:19

有多种技术可以允许线程通信信息。最简单的方法是共享状态上的互斥体。最经典的可扩展方式之一是消息队列。您需要使用的方式取决于您的家庭作业的陈述。

一般来说,使用同步原语(无论是互斥锁、信号量还是其他什么)来保护共享状态,并让非共享状态正常运行。如果您有员工和客户,也许他们通过共享的“邮件槽”进行通信。使用信号量保护该邮件槽,以防止一个人在另一个人正在写入时尝试读取(反之亦然),这样您就拥有了所需的主要策略。

There are multiple techniques for allowing threads to communicate information. The simplest way is a mutex over shared state. One of the most classically scalable ways is message queues. The way that you need to use depends on the statement of your homework assignment.

In general, protect shared state with your synchronization primitive (be it a mutex or semaphore or whatever), and let unshared state run normally. If you have employees and customers, perhaps they communicate via a "mail slot" that they share. Protect that mail slot with your semaphore to prevent one from trying to read while the other is writing (or vice-versa), and you'll have the primary strategy that you need.

愛放△進行李 2024-11-07 05:23:19

另一种方法是通过消息传递。例如,您可以让一个对象订阅事件的侦听器。当另一个线程导致更改时,它会让所有侦听器知道该事件,并且所有侦听器都会收到更改通知。

另一种可能的解决方案是使用管道流或管道读取(即PidedInputStrean、PipedOutputStream、PipedReader、PipedWriter)。在此方案中,一个线程在管道的一侧写入,另一个线程在另一侧读取。

我很确定还有其他几种方法可以做到这一点。

Another ways is by message passing. For instance you can one object subscribe to a listener for events. When the other thread causes a change, then it let all listeners know of the event and all listeners get notified of the change.

Another possible solution is to use piped streams or piped reades (i.e. PidedInputStrean, PipedOutputStream, PipedReader, PipedWriter). In this scheme, one thread writes in one side of the pipe, and the other thread reads the other side.

And I am pretty sure there are several other ways to do it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文