-1

I'm making a simple 2 player multiplayer game using Slick2D in Java. I am using java sockets to create a server and client object. They work fine, however the messaging system is handles in different threads(not to block the main thread). Everything works fine until i try to run code in the main class from the "MessageHandler" Runnable which runs on a child thread. The child threads don't have an OpenGL context so some stuff will not work. Is there a way to call a method in Main class inside the MessageHandler so that it will be executed on the main thread(maybe a new Runnable?)????

user2466076
  • 95
  • 1
  • 12
  • You may look into the techniques used in AWT and Swing to execute a task on the event dispatching thread. This sounds quite similar in my ears. – Ole V.V. Oct 16 '16 at 16:48
  • The problem is that i specifically need to execute on the main thread since that is the only one with an OpenGL context – user2466076 Oct 16 '16 at 16:51
  • There is no such thing as code on a thread. Code is in classes, not threads. Unclear what you're asking. – user207421 Oct 16 '16 at 22:18
  • Use a concurrent list and insert message received from server. In your update method of slick2d check if list has an element, if yes then process it accordingly. This will make sure that the processing is done in the OpenGL context. – Sneh Oct 18 '16 at 14:05

1 Answers1

0

The best solution to your problem would probably be to use your message handling threads to store the messages in a queue (or some other list object). That way, the message handling thread's only job is to listen for messages and to store them. Trying to have the message handling thread to modify objects on the main thread can cause many synchronization issues if not done very carefully, and I don't think is necessary for your case.

The main thread should have a reference to the queue that these messages are being stored too. You can then run a loop (just like you have a loop to draw your game) that's job is to process these messages. If there are no messages to process, the main thread does nothing, and continues on.

It would also be a good idea to synchronize around the list, so that it isn't being written to and read from at the same time.

schwissig
  • 51
  • 2
  • 5