After the Java child thread ends, return information to the main thread (use cloud database to return data in Android)

Project requirements: Android requires that a sub-thread must be restarted to connect to the cloud database, so it involves the return of query data in the sub-thread.
Code:

private void findCourse() {
    
    
    Thread thread = new Thread(new Runnable() {
    
    
        @Override
        public void run() {
    
    
            MySQLUtil mySQLUtil = new MySQLUtil();
            mySQLUtil.getConnection("cce-18");
            course = mySQLUtil.getCourseName("course_info_2018_2019");
        }
    });
    thread.start();
    try {
    
    
        thread.join();
    } catch (InterruptedException e) {
    
    
        e.printStackTrace();
    }
}

  In findCourse, we opened a new child thread, where course is the data we need to return. If we run normally, we will find that: when we need to use course, it is still a null, because the main thread is also in progress, and the child thread has not yet run to initialize the sentence, we are using course, so we must The main thread will continue to run after the course has value after the child thread runs. There are two solutions:

  1. sleep function. This method is not recommended, because we don't know when the child thread ends. If the delay is too long, it will be a waste of resources.
  2. join() function. join() is to wait for the end of the thread calling this method.

Guess you like

Origin blog.csdn.net/Cyril_KI/article/details/108679427