在线程之间传递信息的最佳方法是什么? [英] What is the best way to pass information between threads?

查看:134
本文介绍了在线程之间传递信息的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在我的程序执行其他操作时正在侦听服务器,当我从服务器收到要解释的消息时。

I want to be listening to a server while my program is doing other things, when a message is received from the server I want to interpret it.

我知道线程但不完全确定它是如何工作的。如果我有一个线程监听服务器,我如何将该数据传递给主线程进行解释?主线程将数据发送到服务器的最佳方法是什么? synchronized修饰符有什么用?

I know about threading but not sure completely on how it works. If I have a thread listening for the server how can I pass that data to the main thread for interpretation? What is the best way for the main thread to send data to the server? What is the use of the synchronized modifier?

推荐答案


如果我有一个线程正在侦听服务器如何将该数据传递给主线程进行解释?主线程将数据发送到服务器的最佳方法是什么?

If I have a thread listening for the server how can I pass that data to the main thread for interpretation? What is the best way for the main thread to send data to the server?

我使用 BlockingQueue 。您定义了一个 BlockingQueue ,例如 LinkedBlockingQueue 。您的侦听器类然后调用 queue.take(),它将等待您的服务器调用 queue.put()。它将所有同步,等待,通知等留给Java类而不是你自己的代码。

I'd use a BlockingQueue for this. You define a single BlockingQueue such as the LinkedBlockingQueue. Your listener class then calls queue.take() which will wait for your server to call queue.put(). It leaves all of the synchronization, waits, notifies, etc. to the Java class instead of your own code.


有什么用同步修饰符?

What is the use of the synchronized modifier?

我会做一些阅读以了解更多相关信息。这不是那种可以在简短的SO响应中回答的问题。 Java并发教程是一个很好的起点。

I'd do some reading to understand more about this. This is not the sort of thing that can be answered in a short-ish SO response. The Java concurrency tutorial is a good place to start.

这篇关于在线程之间传递信息的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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