1

I am having a concurrency problem when trying to launch a Javafx Application.

I have written a text-based game, but I also wanted to create my own console to play it in and therefor I made a Console javafx application that works well on its own. I exported the Console as a Jar-file and added it to the build path for my game.

Shortly after the game starts, this snippet is executed, starting a new thread:

public Game(String playerName) {
    player = new Player(playerName);
    try {
        conThread = new ConsoleThread();
        conThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    parser = new Parser(conThread);
    createRooms();
}

The new thread that is started looks like this:

public class ConsoleThread extends Thread{
    public ConsoleThread() {
        Application.launch(Console.class);
    }

    public void printToConsole(String text) {
        Console.printGameInfo(text);
    }

    public String textFromConsole() {
        return Console.getTextField();
    }

This thread class is supposed to launch the Console-application while the main game continues. However, as soon as the application is launched, the Console shows up as intended, but the rest of the game freezes. The main game thread simply stops after starting the new thread and only continues if I manually close the Console-application.

I wanted to have the Console-application work on its own thread, were the player could input text and the main game thread would read it and print something else out. What don't I understand about Java concurrency?

Felix Eder
  • 325
  • 3
  • 16

1 Answers1

2

From the documentation:

The launch method does not return until the application has exited, either via a call to Platform.exit or all of the application windows have been closed.

So your code blocks at new ConsoleThread().

Note also that launch() can only be called once, so, depending on exactly what you're doing here, you may want to rethink the entire strategy here.

Related question: Call JavaFX in Java program and wait for wait to exit before running more code

Community
  • 1
  • 1
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Thanks for your answer! Yes, I didn't read the docs enough, seems like I will need to rethink my strategy when writing this program. Thanks anyway! :D – Felix Eder Jan 26 '17 at 15:28