0

I was told to run all of my MySQL connection processes on another thread besides the main thread to avoid the main thread from being stuck on a process that takes a few seconds to process.

Therefore, I established a ConnectionPool in a separate thread, so that my GUI launches independently from the establishment of the connection. However, this is not the case. When I run the program, it waits until the connection is established and then it actually runs launch(args); My concern is why is it not running independently when a new thread is being established?

public static void main(String[] args) {
    initiateConnection();
    launch(args);
}

private static void initiateConnection() {
    new Thread(() -> {
        try {
            connection = new ConnectionPool("jdbc:mysql://127.0.0.0/comm", "root",
                    "pass");
        } catch (Exception e) {

        }
    }).run();
}
Pablo
  • 1,302
  • 1
  • 16
  • 35

2 Answers2

1

From Javadocs of Thread.run()

If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

So, only the body of lambda expression (which is actually body of the method run of java.lang.Runnable ) is called. It is equivalent to:

    (new Runnable() {

        @Override
        public void run() {
            try {
                connection = new ConnectionPool("jdbc:mysql://127.0.0.0/comm", "root",
                        "pass");
            } catch (Exception e) {

            }
        }
    }).run();
ntahoang
  • 441
  • 5
  • 17
0

You should call .start() instead of .run(). The JVM will call .run on your lambda for you.

Alejandro C.
  • 3,771
  • 15
  • 18
  • What is the difference between the two of them? – Pablo Dec 06 '16 at 14:13
  • `.start` actually causes the thread to begin execution (aka run asynchronously, by spawning a thread and calling `.run` in that thread); `.run` is a synchronous operation. – Alejandro C. Dec 06 '16 at 14:17