2

I am using the following code to open connection to SQL database using JDBC

    Runnable getConn = new Runnable() {
        @Override
        public void run() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
                tracking = true;
                activity.run();
            } catch (SQLException se) {
                se.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    Thread connection = new Thread(getConn);
    connection.run();

it works but it freezes UI thread till connection is opened. Any ideas on how to move this to separate thread so it wont stop UI thread? I was doing this on android using asyncTask but I dont know how to do it in Java.

MWiesner
  • 8,868
  • 11
  • 36
  • 70
horin
  • 1,664
  • 6
  • 23
  • 52

1 Answers1

4

Short Answer

You need to change the connection.run() statement to connection.start().

Long answer

Every Java program begins it's execution with the main thread. In other words, when you run a Java program that has a main method (e.g java MyProgram), a new execution stack is created with the main method at the bottom of this stack.

If a program creates a Thread instance in the main method and calls the start method on the thread instance, a new execution stack will be created with the run method at the bottom of the stack. You will now have two execution stacks. One with the main method at the bottom of the stack and the other with the run method at the bottom of the stack. These two stacks can continue their execution in parallel.

On the other hand, If you call run on a thread instance in the main method instead, it will simply be called in the same execution stack as the main method. A new execution stack will not be created. Therefore, calling run on a thread instance is as good as calling any other method on any other object and has no special meaning.

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82