简体   繁体   English

线程之间的通信

[英]communication between threads

I'm making a little java game in which I would have two threads (well as the FIRST step towards multithreading...), one for the logic and one for the drawing. 我正在制作一个小型Java游戏,其中有两个线程(以及迈向多线程的第一步...),一个用于逻辑,一个用于绘图。

So my question is: How can I make those two communicating which each other? 所以我的问题是:我该如何使这两个彼此交流?

Requirements: 要求:

  • accessing variables and object from a another thread 从另一个线程访问变量和对象

  • syncing them so they each complete a same number of "loops" in the same time. 同步它们,以便它们每个都同时完成相同数量的“循环”。 (the logic calculates and then the another one draws the results and the loop begins again...) (逻辑计算,然后另一个逻辑绘制结果,循环再次开始...)

So how is this achievable in java? 那么如何在Java中实现呢?

Thanks in advance! 提前致谢!

Methods are methods, within a thread or not. 方法是在线程内或不在线程内的方法。 Just create an object that is visible to all of your Threads, and they'll both be able to access it. 只需创建一个对所有线程可见的对象,它们就都可以访问它。

1. Create a Class with logic and drawing methods. 
   Whose object is accessible by both the threads.

2. Now please do synchronize the atomic statements or methods.

3. So its like an object is shared between 2 threads.

One easy structure to use to communicate between threads is the BlockingQueue . 一种用于在线程之间进行通信的简单结构是BlockingQueue

I often find if you use a BlockingQueue it will focus you on making the threads work together correctly. 我经常发现,如果您使用BlockingQueue它将使您专注于使线程正确协同工作。 For example, they will not provide the facilities you are asking for because actually those facilities are not what you want. 例如,他们不会提供您所要求的设施,因为实际上这些设施不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM