Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing 2 things at the same time in Java

Tags:

java

Well, I'm working on an online game in Java. I have a client and a server. And the speech system waits for a new message to be displayed like this:

public void addSpeech(String msg) {
    String newMsg = parsel10n(msg);
    m_narrator.addSpeech(parsel10n(newMsg));
    while (!m_narrator.getCurrentLine().equalsIgnoreCase(newMsg))
      ;
    while (!m_narrator.getAdvancedLine().equalsIgnoreCase(newMsg))
      ;
 } 

The problem is.. the rest of the application stops because of the while loops. I don't see any other players move or see the chat while in this loop. Is there a way I could run this method without touching the rest of the application (client) with the loops? Should threads be involved? I hope you'd be able to answer me.

like image 628
Fabian Pas Avatar asked Dec 01 '25 09:12

Fabian Pas


1 Answers

Yes, threads should be involved.

If you just want to launch a task in parallel of your main execution thread, you might do this :

new Thread(){
   public void run(){
        addSpeech();
   }
}.start();

But you'll have to check your data structures can be accessed from more than one thread.

And you might want to do something on end of task, etc. So I suggest you look for a tutorial about java threads and task queues.

like image 96
Denys Séguret Avatar answered Dec 02 '25 23:12

Denys Séguret