Some thoughts on the location of the startup thread

Recently I saw two similar pieces of code, the first one is

public class Main {
    
    
    public static void main(String[] args) {
    
    
        new Thread(() -> {
    
    
            doWork();
        }).start();
    }
    
    static void doWork(){
    
    
        //执行耗时操作...
    }
}

The second paragraph is

public class Main {
    
    
    public static void main(String[] args) {
    
    
        doWork();
    }

    static void doWork() {
    
    
        new Thread(() -> {
    
    
            //执行耗时操作...
        }).start();
    }
}

The only difference between the two pieces of code is where the thread is started.

Sometimes when writing a program more casually, both forms of code may appear. Here are some of my thoughts on this form.

The first type: the caller controls thread startup

This corresponds to the above situation of starting the thread in the main method. This form was first seen in a Activity code in Android, because many methods of Activity run in the main thread. If time-consuming operations are performed, , then the ANR program will not respond, and some operations that are considered time-consuming will be placed in other threads, so there is similar code:

public class DemoActivity extends Activity{
    
    

    @Override
    protected void onResume() {
    
    
        super.onResume();
        new Thread(() -> {
    
    
            xxManager.startDoWorks();
        }).start();
    }
}

The second type: the implementation controls thread startup

This corresponds to the second situation above where the thread is started in the doWork method. This kind of code was first seen in a code of Controller. Because this class contains some network and file access operations, the interface methods start a separate thread for execution:

public class DemoController{
    
    

    public void doXXXWork(Callback callback){
    
    
        new Thread(() -> {
    
    
            //执行耗时操作...
        }).start();
    }
}

Compare and think

Although I have written both codes, I still prefer the latter to let the implementation control thread startup. The reasons are as follows:

  1. The implementer knows the specific implementation of the internal code and can decide in which type of thread the internal code is executed. The caller needs to look at the implementation's code to know.
  2. The implementer has control over the implemented code and can change the code implementation and adjust the use of threads according to the implementation method.
  3. It feels a bit overreaching for the caller to change the thread context of external code. This should not be the caller's responsibility.

Guess you like

Origin blog.csdn.net/zssrxt/article/details/131876604