同步异步任务的最佳方法 [英] Best way to synchronize asynchronous task

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

问题描述

我的问题:我已将802.15.4无线网络连接到串行端口(使用包装器). 我可以将程序包发送到网络中,并监听传入的程序包. 可以想象,这是高度异步的.

My Problem: I've got 802.15.4 Wireless network connected to a serial port (using a wrapper). I can send packages into the network and listen for incoming packages. As you can imagine this is highly asynchronous.

任务来了:我想将命令发送到网络,并在一个函数调用中等待响应.例如:我要从网络ID为1338的节点获取温度.

Here comes the task: I want to send commands to the network and wait for the response in one function call. For Example: I want to get the temperature from the Node with the network ID 1338.

double getTemperature(int id) throws Exception { .... }

除了做所有这些"synchonized(object)wait(..)notify(..)"之类的东西以外,还有更好的等待响应消息的方法吗?

Is there a better way of waiting for a response message other than doing all this "synchonized(object) wait(..) notify(..)" stuff?

最诚挚的问候, 大波恩

Best regards, bigbohne

也许要添加一些香料:

所有这些都应以用户可以(通过ajax或直接)请求这些命令的Web界面结束.我还考虑过在数据库中缓存响应值. 但是对于某些命令,MUSS可以直接回答成功/失败

This should all end in a webinterface where user can request these commands (either through ajax or directly). I've also thought of caching responce values in a database. But for some commands you MUSS have a direct answer of success/failure

推荐答案

您可以使用BlockingQueue进行此操作,因此您不必手动管理任何同步.请求可以发送消息,然后在BlockingQueue上调用take(),它将等待元素出现.元素是回复,当回复返回时,您在端口上拥有的任何侦听器都将其插入队列中.

You can do this with a BlockingQueue so you will not have to manually manage any of the synchronization. The request can send the message, then call take() on a BlockingQueue which will wait for an element to be present. The element is the reply which is inserted into the queue by whatever listener you have on the port when the reply is returned.

您只需要进行协调,以便侦听器和请求者共享同一队列.每个请求只需要一个大小为1的队列即可支持这种情况.

You just have to coordinate so that the listener and requester share the same queue. You only need a queue of size one for each request to support this scenario.

// Send method
BlockingQueue<Reply> q = new ArrayBlockingQueue<Reply>(1);
serialCom.registerQueue(myRequest.getId());
serialCom.sendRequest(myRequest);
return q.take();

//Listener
BlockingQueue<Reply> q = queueMap.get(incomingMessage.getId());
q.add(incomingMessage.getReply());

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

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