开发者

Java Thread communicaton

开发者 https://www.devze.com 2023-02-23 04:42 出处:网络
I am doing a project in which I must make threads communicate. For instance I have two thread arrays, c[100] and e[10]. (c开发者_StackOverflow中文版ustomers and employees)

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

For instance

I have two thread arrays, c[100] and e[10]. (c开发者_StackOverflow中文版ustomers 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?


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.


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.

0

精彩评论

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

关注公众号