线程同步 [英] Thread syncronization

查看:84
本文介绍了线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个有3个线程的应用程序. 让我们称它们为a,b,c.

I am developing an application in which I have 3 threads. Let us call them a,b,c.

现在我必须开发类似这样的东西.

Now I have to develop something like this.

最初,b等待a完成任务,而c等待b.

Initially b waits for a to complete its task, and c waits for b.

一旦"a"完成其任务,便通知"b". 'b'应该醒来.现在,"a"进入等待状态. 'a'会一直等到它得到'c'的确认.

As soon as 'a' finishes its task it notifies 'b'. 'b' should wake up. Now 'a' goes to wait state. 'a' will wait until it gets an acknowledgement from 'c'.

现在b完成任务并通知'c'.现在,"c"醒来,"b"进入等待状态.

Now b finishes its task and notifies 'c'. Now 'c' wakes up and 'b' goes to wait state.

现在c完成任务并确认为"a".现在,"c"要等待.

Now c finishes the task and acknowledges to 'a'. Now 'c' goes to wait.

这是循环过程,从a-> b,b-> c,c-> a

This is circular process and continues from a -> b , b -> c, c->a

在此周期之间,所有线程都访问队列以进行数据传输,即'a'将数据放入队列q1,'b'提取数据并放入另一个队列q2,'c'从q2提取并处理并将其返回给'一个'

In between this cycle all threads access queues for data transfer i.e. 'a' puts data in queue q1, 'b' fetches it and puts in another queue q2, 'c' fetches from q2 and process it and give back to 'a'

在实施此功能时,我陷入了困境. 关于如何做到这一点的任何想法?

I am stuck while implementing this functionality. Any idea about how this can be done?

谢谢...

推荐答案

如果允许您使用队列(这似乎是作业),那么您可以做些更优雅的事情.最终的内部锁定可能类似于带有信号灯的解决方案,但更为优雅.

If you are allowed to use queues (it seems homework) then you can do something more elegant. Probably the resultant internal lockings are similar to solutions with semaphores, but more elegant.

创建3个队列,每对进程一个.他们不发送真实数据,只是发送信号.

Create 3 queues, one for each pair of processes. They don't send real data, just the signal to start.

Queue<Integer> queueA2B = new BlockingQueue<Integer>();
Queue<Integer> queueB2C = new BlockingQueue<Integer>();
Queue<Integer> queueC2A = new BlockingQueue<Integer>();

// initialize only the queue that *feeds* A:

queueC2A.put(1);

每个进程都必须从其队列中取出一个项目,执行它的流程,然后向下一个发送信号.例如A:

Each process must take an item from its queue, do its process and send a signal to the next. By example A:

while (...) {
   queueC2A.take(); // this will block until there's something in the queue
   // do my stuff
   queueA2B.put(1); // send "signal" to the next process
}

这篇关于线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆